我有一些对象,比如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的变化。
我想我可以使用__proto__
属性在Firefox,像
var father = {
firstProperty: someValue;
secondProperty: someOtherValue;
};
var son = {
thirdProperty: yetAnotherValue
__proto__: father
};
son.constructor.prototype = father;
但是,据我了解,这是不是语言的标准功能,它是最好不要直接使用它。
有没有一种方法来指定对象文字的原型?
http://stackoverflow.com/questions/1592384/adding-prototype-to-object-literal – 2012-12-01 20:04:36