【问题标题】:Adding a prototype to an object literal将原型添加到对象字面量
【发布时间】:2010-08-10 18:57:20
【问题描述】:

我有一些对象,比如son,我想从另一个对象father 继承它。

当然我可以为父亲做一个构造函数,比如

Father = function() {
  this.firstProperty = someValue;
  this.secondProperty = someOtherValue;
}

然后使用

var son = new Father();
son.thirdProperty = yetAnotherValue;

但这并不是我想要的。由于son 将具有许多属性,因此将儿子声明为对象文字会更具可读性。但是我不知道如何设置它的原型。

做类似的事情

var father = {
  firstProperty: someValue;
  secondProperty: someOtherValue;
};
var son = {
  thirdProperty: yetAnotherValue
};
son.constructor.prototype = father;

不会起作用,因为原型链似乎是隐藏的,并不关心constructor.prototype的变化。

我想我可以在 Firefox 中使用 __proto__ 属性,比如

var father = {
  firstProperty: someValue;
  secondProperty: someOtherValue;
};
var son = {
  thirdProperty: yetAnotherValue
  __proto__: father
};
son.constructor.prototype = father;

但是,据我了解,这不是该语言的标准功能,最好不要直接使用它。

有没有办法为对象字面量指定原型?

【问题讨论】:

标签: javascript oop prototype-programming


【解决方案1】:

你说得对,__proto__ 是一个非标准属性,设置新对象的[[Prototype]] 的唯一两种标准方法是:

  • 通过使用构造函数和new 运算符(正如您已经提到的)。
  • 使用 ECMAScript 5 Object.create 方法。

Object.create 还不是widely supported(适用于 IE9Pre3+、Firefox 3.7Alpha+、Chrome 5+ Safari 5+、Rhino 1.7),但在某些时候所有实现都将符合 ES5 规范。

它可以有两个参数,第一个是将用作新对象的[[Prototype]] 的对象,第二个是另一个可以描述自身属性的对象(在相同的结构中你会使用Object.defineProperties)。

例如:

var father = {
  firstProperty: 1,
  secondProperty: 2
};

var son = Object.create(father, {
  thirdProperty: {
    value: 'foo'
  }
});

father.isPrototypeOf(son); // true
son.firstProperty; // 1

son 内部的[[Prototype]] 属性将引用father,它将包含一个名为thirdProperty 的值属性。

【讨论】:

  • 您的回答清除了我所有的疑虑,但遗憾的是 Object.create 的语法(带有附加的“值:”)似乎更不可读。
  • 是的,为什么他们不能创建一个简单地接受对象文字的函数。我的意思是,大多数时候我们只关心键和值,而不关心属性元数据,比如将其设为只读。
【解决方案2】:

这是不正确的 jmar777。例如,如果您有

var X = function() {};
X.prototype = {
  protoFunc1: function() { console.log('p1');},
  protoFunc2: function() { console.log('p2');}
};

X.protoFunc1(); // is not a function 

这意味着你在做什么:

X.prototype = {}

只是创建一个名为原型的对象。不是实际的原型。要使用原型,您必须使用构造函数。

如果你把它修改成这个(构造方法)

function X(){};
X.prototype.protoFunc1 = function() { 
    console.log('p1');
}
X.prototype.protoFunc2 = function() { 
    console.log('p2');
}

var x = new X();
x.protoFunc1(); //'p1'

它会起作用的。

要么使用不使用原型的对象字面量方法,要么使用使用原型的构造器方法。

【讨论】:

    【解决方案3】:

    为对象字面量指定原型有点“古怪”,因为您主要需要使用构造函数语法(例如,new X())创建的对象上的原型。不是说这是不可能的……但这很奇怪。一个经过充分证明的类似模式(例如,由 jQuery 使用)是将原型定义为对象字面量。例如:

    var X = function() {};
    X.prototype = {
      protoFunc1: function() {},
      protoFunc2: function() {}
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-22
      • 2010-12-08
      • 2017-06-06
      • 2016-11-02
      • 2013-06-20
      相关资源
      最近更新 更多