将原型添加到对象文字中 [英] Adding a prototype to an object literal
问题描述
我有一些对象,比如 son
,我想继承另一个对象 father
。
I have some object, say son
, which I'd like to inherit from another object father
.
当然我可以为父做一个构造函数,比如
Of course I can make a constructor function for father, like
Father = function() {
this.firstProperty = someValue;
this.secondProperty = someOtherValue;
}
然后使用
var son = new Father();
son.thirdProperty = yetAnotherValue;
但这不是我想要的。由于 son
将具有许多属性,因此将子声明为对象文字将更具可读性。但后来我不知道如何设置其原型。
but this is not exactly what I want. Since son
is going to have many properties, it would be more readable to have son declared as an object literal. But then I don't know how to set its protoype.
做类似的事情
var father = {
firstProperty: someValue;
secondProperty: someOtherValue;
};
var son = {
thirdProperty: yetAnotherValue
};
son.constructor.prototype = father;
不起作用,因为原型链似乎是隐藏的而不关心构造函数的更改。原型。
will not work, as the prototype chain seems to be hidden and not care about the change of constructor.prototype.
我想我可以在Firefox中使用 __ proto __
属性,例如
I think I can use the __proto__
property in Firefox, like
var father = {
firstProperty: someValue;
secondProperty: someOtherValue;
};
var son = {
thirdProperty: yetAnotherValue
__proto__: father
};
son.constructor.prototype = father;
但据我所知,这不是该语言的标准功能,它更好不要直接使用它。
but, as far as I understand, this is not a standard feature of the language and it is better not to use it directly.
有没有办法为对象文字指定原型?
推荐答案
你是对的, __ proto __
是一个非标准的属性,你只有两种标准方式设置一个新对象的 [[Prototype]]
,是:
You're right, __proto__
is a non-standard property, and the only two standard ways you have to set a new object's [[Prototype]]
, are:
- 通过使用构造函数和
new
运算符(如您所述)。 - 使用ECMAScript 5
Object.create
方法。
- Through the use of a constructor and the
new
operator (as you already mention). - Using the ECMAScript 5
Object.create
method.
Object.create
不是广泛支持(适用于IE9Pre3 +,Firefox 3.7Alpha +,Chrome 5+ Safari 5+, Rhino 1.7),但在某些时候所有实现都符合ES5规范。
Object.create
is not widely supported yet (works on IE9Pre3+, Firefox 3.7Alpha+, Chrome 5+ Safari 5+, Rhino 1.7), but at some point all the implementations will conform the ES5 spec.
它可以有两个参数,第一个是将用作的对象新对象的 [[Prototype]]
,第二个是另一个可以描述自己属性的对象(与你使用的结构相同 Object.defineProperties
)。
It can take two arguments, the first one is the object that will be used as the [[Prototype]]
of the new object, and the second one, is another object where the own properties can be described (in the same structure that you would use Object.defineProperties
).
例如:
var father = {
firstProperty: 1,
secondProperty: 2
};
var son = Object.create(father, {
thirdProperty: {
value: 'foo'
}
});
father.isPrototypeOf(son); // true
son.firstProperty; // 1
儿子
内部 [[Prototype]]
属性将引用 father
,它将包含一个名为的值属性thirdProperty
。
The son
internal [[Prototype]]
property will refer to father
, and it will contain a value property named thirdProperty
.
这篇关于将原型添加到对象文字中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!