我正在看一个使用原型(prototype)的继承示例,如下所示:
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)
来设置原型(prototype),为什么不像 Person.prototype
那样简单地设置它?
最佳答案
如果你这样做
Student.prototype = Person.prototype;
下一步尝试扩展它:
Student.prototype.a = function(....
你也会影响 Person.prototype
(因为它在赋值后是完全相同的对象)
关于javascript - 为什么在原型(prototype)继承中需要使用 Object.create(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70071548/