在设置Prototype的Prototype之前使用Prototype的属性

时间:2014-12-16 13:14:10

标签: javascript

我想将一个属性赋给函数的原型,并在将原型设置为函数原型之前使用该属性(很难解释)。如果我在Java中这样做,我只会在基类上创建一个public static final变量。例如......

function Foo(a, b) {
    this.a = a;
    this.b = b;
}

function Bar() {
   this.prototype.A = 100; 
   this.prototype.B = 250;
   Foo.call(this, this.prototype.A, this.prototype.B);
}
Bar.prototype = Object.create(Foo); // Bar.A and Bar.B are now undefined, not what I
                                    // want to happen.

潜在的实施#1 ......

function Foo(a, b) {
    this.a = a;
    this.b = b;
}

var tempA = 100;
var tempB = 250;

function Bar() {
    Foo.call(this, tempA, tempB);
}
Bar.prototype = Object.create(Foo);
Bar.prototype.A = tempA;
Bar.prototype.B = tempB;

潜在的实施#2 ......

function Foo(a, b) {
    this.a = a;
    this.b = b;
}

var barPrototype = Object.create(Foo);
barPrototype.A = 100;
barPrototype.B = 250;

function Bar() {
    Foo.call(this, barPrototype.A, barPrototype.B);
}
Bar.prototype = barPrototype;

是否有人更喜欢哪种实施更好?或者是否有更优雅的方式(没有临时变量)来做到这一点?

1 个答案:

答案 0 :(得分:1)

您是否只想扩展Foo的原型并为其添加其他属性?为此你可以使用这样的东西:

function Bar() {
  new Foo.call(this, this.A, this.B); // It's a constructor, should use new
}

var proto = Object.create(Foo.prototype);
proto.A = 100;
proto.B = 250;

Bar.prototype = proto;

但是,如果你想进一步扩展它,那么你真的在寻找一个 mixin 方法,它允许你将两个对象合并在一起。 如果你已经在使用jQuery(注意:绝对不是为了这个目的而提倡),你可以使用 $.extend() 方法:

Bar.prototype = $.extend({}, Foo.prototype, {
  A: 100,
  B: 250
});

如果您不使用jQuery,在其他地方找到类似的方法应该不难(例如,Underscore也有一个)


如果您希望拥有共享变量,以便FooBar都可以使用,那么您也可以将其定义包装在Immediately-Invoking Function Expression (IIFE)中并在此函数中定义您的A和B私有变量:

(function() {
  var A = 100,
      B = 250;

  function Foo() { ... }

  function Bar() {
    Foo.call(this, A, B);
  }
})();

如果A和B是更多的全局常量,并且与Bar没有内在联系,那么这将更合适。