繁体   English   中英

将原型添加到对象文字中

[英]Adding a prototype to an object literal

我有一些对象,比如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;

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

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

你是对的, __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

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

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

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

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

这意味着你在做什么:

X.prototype = {}

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

但是如果你修改它(构造函数方法)

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

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

它会工作。

要么在不使用原型的情况下使用对象文字方法,要么使用原型使用构造方法。

为对象文字指定原型有点“不可思议”,因为您主要想要使用构造函数语法(例如,new X())创建对象的原型。 不是说这是不可能的......但这很奇怪。 一个类似的模式已被充分证明(例如,由jQuery使用),而是将原型定义为对象文字。 例如:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM