【发布时间】: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