我试图从我的javascript构造函数的构造函数调用一个方法,这是可能的,如果是这样,我似乎无法使它工作,任何洞察力都会很棒!谢谢!
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");
}
我得到它与上面的内容一起工作,但我似乎无法访问CreateErrorList函数中的'errArray'变量。
是的,有可能在构造函数执行时,this
值已经指向[[Prototype]]
对象的ValidateFields.prototype
内部属性。
现在,通过查看您的编辑,errArray
变量在CreateErrorList
方法的范围内不可用,因为它仅绑定到构造函数本身的范围。
如果您需要将此变量保持为私有且仅允许CreateErrorList
方法访问它,则可以在构造函数中将其定义为特权方法:
function ValidateFields(pFormID){
var aForm = document.getElementById(pFormID);
var errArray = [];
this.CreateErrorList = function (formstatid){
// errArray is available here
};
//...
this.CreateErrorList();
}
请注意,该方法,因为它绑定到this
,将不会被共享,它将物理存在于ValidateFields
的所有对象实例上。
另一种选择,如果你不介意将errArray
变量作为对象实例的公共属性,你只需将它分配给this
对象:
//..
this.errArray = [];
//..
更多信息:
解:
function ValidateFields(pFormID){
console.log("ValidateFields Instantiated");
var aForm = document.getElementById(pFormID);
this.errArray = new Array();//error tracker
this.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
}
希望这有助于将来可能有这样的问题的任何人。