将原型添加到对象文字中

And*_*rea 7 javascript oop prototype-programming

比方说son,我有一些对象,我想从另一个对象继承father.

当然我可以为父亲创建一个构造函数

Father = function() {
  this.firstProperty = someValue;
  this.secondProperty = someOtherValue;
}
Run Code Online (Sandbox Code Playgroud)

然后使用

var son = new Father();
son.thirdProperty = yetAnotherValue;
Run Code Online (Sandbox Code Playgroud)

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

做点什么

var father = {
  firstProperty: someValue;
  secondProperty: someOtherValue;
};
var son = {
  thirdProperty: yetAnotherValue
};
son.constructor.prototype = father;
Run Code Online (Sandbox Code Playgroud)

不会起作用,因为原型链似乎是隐藏的而不关心构造函数.prototype的变化.

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

var father = {
  firstProperty: someValue;
  secondProperty: someOtherValue;
};
var son = {
  thirdProperty: yetAnotherValue
  __proto__: father
};
son.constructor.prototype = father;
Run Code Online (Sandbox Code Playgroud)

但是,据我所知,这不是该语言的标准功能,最好不要直接使用它.

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

CMS*_*CMS 11

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

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

Object.create尚未广泛支持(适用于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
Run Code Online (Sandbox Code Playgroud)

son内部[[Prototype]]属性将指father,它将包含一个名为Value属性thirdProperty.