Calling A Method In A Javascript Constructor And Accessing Its Variables
Solution 1:
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:
functionValidateFields(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:
Solution 2:
Answer :
functionValidateFields(pFormID){
console.log("ValidateFields Instantiated");
var aForm = document.getElementById(pFormID);
this.errArray = newArray();//error trackerthis.CreateErrorList(); //calling a constructors method
}
ValidateFields.prototype.CreateErrorList = function(){
console.log("Create Error List");
console.log(this.errArray); //this is how to access the constructors variable
}
Hope this helps anyone who might have a question like this in the future.
Solution 3:
Are you creating an object of ValidateFields
somewhere?
Edit: You need to prepend this
whenever referring to a function's public properties.
Updated the code here: http://jsbin.com/afiru/edit
Post a Comment for "Calling A Method In A Javascript Constructor And Accessing Its Variables"