在Javascript构造函数中调用方法并访问其变量 [英] Calling a method in a Javascript Constructor and Accessing Its Variables

查看:126
本文介绍了在Javascript构造函数中调用方法并访问其变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从我的javascript构造函数的构造函数中调用一个方法,这是否可能,如果是这样,我似乎无法使其工作,任何洞察力都会很棒!谢谢!

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");
 }

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

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

推荐答案

是的,当你的构造函数执行时,有可能值已经指向 ValidateFields.prototype <的 [[Prototype]] 内部属性/ code> object。

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

现在,通过查看您的编辑, errArray 变量不是可以在 CreateErrorList 方法的范围内使用,因为它只绑定到构造函数本身的范围。

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.

如果您需要保留此变量 private 并且只允许 CreateErrorList 方法来访问它,您可以将其定义为特权方法,在构造函数中:

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();
}

注意方法,因为它绑定到这个,不会共享,它将在 ValidateFields 的所有对象实例上实际存在。

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.

另一种选择,如果你不介意将 errArray 变量作为你的 public 属性对象实例,你只需要将它分配给这个对象:

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 = [];
//..

更多信息:

  • Private Members in JavaScript
  • Closures

这篇关于在Javascript构造函数中调用方法并访问其变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆