在Javascript构造函数中调用方法并访问其变量

alv*_*spo 27 javascript methods constructor prototype

我试图从我的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");
 }
Run Code Online (Sandbox Code Playgroud)

我得到它与上面的内容一起工作,但我似乎无法访问CreateErrorList函数中的'errArray'变量.

CMS*_*CMS 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();
}
Run Code Online (Sandbox Code Playgroud)

请注意,该方法,因为它的绑定this,将不会被共享,它将物理存在于所有对象实例上ValidateFields.

另一个选项,如果您不介意将errArray变量作为对象实例的公共属性,则只需将其分配给this对象:

//..
this.errArray = [];
//..
Run Code Online (Sandbox Code Playgroud)

更多信息:


alv*_*spo 8

解:

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
}
Run Code Online (Sandbox Code Playgroud)

希望这有助于将来可能有这样的问题的任何人.