为什么在原型继承中需要使用Object.create()?

3

我正在查看一个使用原型的继承示例,如下:

function Person(name){
   this.name = name
}

function Student(name){
  Person.call(this, name)
}
Student.prototype = Object.create(Person.prototype)
Student.prototype.constructor = Student

let jim = new Student("Jim")

我的问题是,为什么需要使用Object.create(Person.prototype)来设置原型?为什么不能像这样简单地设置:Person.prototype

1个回答

2

如果您进行

Student.prototype = Person.prototype;

接下来的步骤是尝试扩展它:

Student.prototype.a = function(....

由于它在赋值后严格地成为完全相同的对象,因此您也将影响Person.prototype


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接