【发布时间】:2015-01-15 16:22:54
【问题描述】:
i was answering to a question where i encountered this problem 在下面的代码中,如何使用 object.create() 方法将孩子的原型设置为父级。我可以使用
child.prototype=new Parent();
但我想使用 object.create.using child.prototype=Object.create(Parent) 来实现,但没有将原型设置为 Parent
function Parent() {
this.parentFunction = function(){
console.log('parentFunction');
}
}
Parent.prototype.constructor = Parent;
function Child() {
this.parentFunction = function() {
this.constructor.prototype.parentFunction.call(this);
console.log('parentFunction from child');
}
}
Child.prototype = Object.create(Parent);
Child.prototype.constructor = Child;
var child = new Child();
console.dir(child);
child.parentFunction();
【问题讨论】:
-
Object.create使用给定的原型创建一个新对象。你已经有一个对象,你只是想改变它的原型,所以Object.create似乎只是改变原型的错误方法。 -
Child.prototype = Object.create(Parent.prototype);。尽管这样做没有任何价值,因为您没有向Parent.prototype添加任何内容。您还缺少其他东西。看看Benefits of usingObject.createfor inheritance。 -
@FelixKling 谢谢!!但请你详细说明!!我还没有定义父母的原型。声明似乎令人困惑
-
看看另一个问题,我想我的回答解释了你需要知道的一切。
Object.create(Parent)将创建一个在其原型链中具有 函数Parent的新对象。那不是你想要的。理想情况下,parentFunction将在Parent.prototype上定义。 -
我建议您在 Child-Constructor 中使用 Parent.call(this) 以便能够以实例继承方式继承父方法。
标签: javascript prototype prototype-chain