簡體   English   中英

原型構造函數調用

[英]Prototype Constructor Call

除了使用call方法,還可以使用以下方法,例如:

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

歡迎任何建議。

干杯

您可以這樣做,但真是一團糟。 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更改為從另一個類繼承。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM