使用Object.create实现原型继承
function Base() {}
Base.prototype.say=function(){
console.log("base say")
}
function Derived() {}
Derived.prototype = Object.create(Base.prototype);
Derived.prototype.derivedSay=function(){
}
const obj = new Derived();
console.log("obj",obj)
obj.say()
使用Object.setPrototypeOf实现原型继承
function Base() {}
Base.prototype.say=function(){
}
function Derived() {}
Derived.prototype.derivedSay=function(){
}
// 将 `Derived.prototype` 的 `[[Prototype]]`
// 设置为 `Base.prototype`
Object.setPrototypeOf(Derived.prototype, Base.prototype);
const obj = new Derived();
对比&&总结
Object.create实现属性继承时候,重新为 prototype
属性赋值,同时删除原型对象的constructor属性
所以需要从新更新原型对象的构造函数指向
Derived.prototype.constructor=Derived;