我正在学习 JS OOP 的东西,发现了一个令我困惑的案例。在下面的代码片段中,我使用Object.create
方法来实现继承。
function Parent(){
this.name = "wang";
}
function Child(){
this.age = 28;
}
Child.prototype = Object.create(Parent.prototype)
var mychild = new Child();
console.log(mychild.name)
mychild.name
未定义。
但是如果我使用new Parent()
来完成继承部分,它可以按如下方式工作:
function Parent(){
this.name = "wang";
}
function Child(){
this.age = 28;
}
Child.prototype = new Parent();
var mychild = new Child();
console.log(mychild.name)
我曾经读过一些教程,其中说实际上 Object.create
方法是正确的遵循方法。那么我的代码有什么问题吗?
最佳答案
您的第一个示例对于继承来说是正确的,但请务必注意,您尚未在新创建的 Child
实例上调用 Parent
函数。
为此,您可以使用call
或apply
:
function Child() {
Parent.call(this)
this.age = 28
}
function Parent(){
this.name = "wang";
}
function Child(){
Parent.call(this);
this.age = 28;
}
Child.prototype = Object.create(Parent.prototype);
var mychild = new Child();
console.log(mychild.name);
如果你使用的是ES2015,你可以使用class
来简化代码:
class Parent {
constructor() {
this.name = "wang"
}
}
class Child extends Parent {
constructor() {
super()
this.age = 28
}
}
const mychild = new Child()
console.log(mychild.name)
请注意,在后面的示例中,super
取代了 Parent.call(this)
。
关于javascript - 关于原型(prototype)继承的一个令人困惑的案例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43245086/