javascript - 关于原型(prototype)继承的一个令人困惑的案例

标签 javascript oop inheritance

我正在学习 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 函数。

为此,您可以使用callapply:

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/

相关文章:

javascript - postMessage 在 IE11 上仍然损坏?

javascript - 单击复选框时如何更改按钮的颜色

c# - 这是糟糕的 oop 设计吗?

java - 如何为空参数进行方法重载?

python - 当子类用 __init__() 调用 super() 时,父类(super class)的对象在哪里/什么?

javascript - 删除单词后的字符,javascript

c# - 类中的组方法

inheritance - Kotlin 覆盖成员集并获取

.net - 逻辑及其在 Collections.Generic 和继承中的应用

javascript - 以功能方式交换两个数组元素