我试图从我的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'变量。
答案 0 :(得分:19)
是的,当构造函数执行时,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
变量作为对象实例的 public 属性,则只需将其分配给{{1}对象:
this
更多信息:
答案 1 :(得分:7)
<强>解决方案:强>
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
}
希望这有助于将来可能会遇到类似问题的任何人。
答案 2 :(得分:0)