Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a method in a Javascript Constructor and Accessing Its Variables

I am trying to call a method from the constructor of my javascript constructor, is this possible and if so, I can't seem to get it working, any insight would be great! Thanks!

function ValidateFields(pFormID){     var aForm = document.getElementById(pFormID);     this.errArray = new Array();//error tracker     this.CreateErrorList(); } /*  * CreateErrorList()  * Creates a list of errors:  *   <ul id="form-errors">  *    <li>  *     You must provide an email.  *    </li>  *   </ul>  * returns nothing  */  ValidateFields.prototype.CreateErrorList = function(formstatid){      console.log("Create Error List");  } 

I got it to work with what is above, but I can't seem to access the 'errArray' variable in CreateErrorList function.

like image 215
alvincrespo Avatar asked Feb 19 '10 05:02

alvincrespo


People also ask

Can you call a method in a constructor JavaScript?

Yes, it is possible, when your constructor function executes, the this value has already the [[Prototype]] internal property pointing to the ValidateFields.

Can we call method within constructor?

Yes, as mentioned we can call all the members of a class (methods, variables, and constructors) from instance methods or, constructors.

What is the method for constructor in JavaScript?

The constructor() method is called automatically when a class is initiated, and it has to have the exact name "constructor", in fact, if you do not have a constructor method, JavaScript will add an invisible and empty constructor method. Note: A class cannot have more than one constructor() method.


1 Answers

Yes, it is possible, when your constructor function executes, the this value has already the [[Prototype]] internal property pointing to the ValidateFields.prototype object.

Now, by looking at the your edit, the errArray variable is not available in the scope of the CreateErrorList method, since it is bound only to the scope of the constructor itself.

If you need to keep this variable private and only allow the CreateErrorList method to access it, you can define it as a privileged method, within the constructor:

function ValidateFields(pFormID){   var aForm = document.getElementById(pFormID);   var errArray = [];    this.CreateErrorList = function (formstatid){     // errArray is available here   };   //...   this.CreateErrorList(); } 

Note that the method, since it's bound to this, will not be shared and it will exist physically on all object instances of ValidateFields.

Another option, if you don't mind to have the errArray variable, as a public property of your object instances, you just have to assign it to the this object:

//.. this.errArray = []; //.. 

More info:

  • Private Members in JavaScript
  • Closures
like image 50
Christian C. Salvadó Avatar answered Oct 16 '22 23:10

Christian C. Salvadó