原型构造函数调用

时间:2010-12-30 09:04:49

标签: javascript

不是使用调用方法,而是适用于以下内容,例如:

var A = function(height,weight) {
    this.height = height;
    this.weight = weight;
};

var a = new A("6ft","500lbs");

A.prototype.foo = {
    setup: function() {
        this.height.set();
        this.weight();
    },

    height: {
        set: function() {
            var constr = a;
            var self = this;

            console.log(constr);
            console.log(self);
        }
    },

    weight: function() {
        var constr = a;
        var self = this;

        (function() {
            console.log(constr);
        })();
    }
};

a.foo.setup();

欢迎任何建议。

干杯

1 个答案:

答案 0 :(得分:1)

你可以做到这一点,但真是一团糟。 heightweight有两种不同的含义; A的所有实例都会引用该初始a。你想要完成什么?

修改

使用原型的问题在于,当创建一个原型时,没有特定于实例的功能上下文(原因很明显,原型只创建一次,通常在类的任何实例之前。没有上下文,没有地方可以将变量隐藏到实例私有。我更喜欢在构造时创建方法:

var A = function(height, weight) {
    this.height = function() { return height; };
    this.weight = function() { return weight; };
};

使用函数创建原型本身会为所有实例创建一个公共(私有,静态)上下文。你甚至可以混合概念:

var A = function(height, weight) {
    this.__init__(height, weight);
};

A.prototype.__init__ = (function() {
   // any variables declared here are private and static
   var number_of_instances = 0;
   return function(height, weight) {
      // any variables declared here are private and NOT static

      // as always, anything added to this are public and not static
      this.getNumberOfInstances = function() {
          return number_of_instances;
      };

      this.height = function() { return height; };
      this.weight = function() { return weight; };
      number_of_instances++;
   };
})();

我对编写整个原型感到不满意,这意味着您无法将A更改为从其他类继承。