JS继承和原型分配

js inheritance and prototype assignment

本文关键字:分配 原型 继承 JS      更新时间:2023-09-26

我正在学习JS原型和继承,我了解到正确的方法是:

function A(){}
A.prototype.doSomething=function(){}
function B(){}
B.prototype = new A();
console.log( (new B()) instanceof A);//true
console.log( (new B()) instanceof B);//true

如您所见,我正在将 A 的新实例设置为 B但如您所见,它适用于

function A(){}
A.prototype.doSomething=function(){}
function B(){}
B.prototype = A.prototype;
console.log( (new B()) instanceof A);//true
console.log( (new B()) instanceof B);//true

但在这里:http://ejohn.org/apps/learn/#76

他们声称原型分配是错误的,我不明白为什么?

下面是第一个示例中的原因:

console.log( (new B()) instanceof A);//true

console.log( (new A()) instanceof B);//true

所以这是错误的用法。
正确的方法是以下一种方式执行此操作:

function Parent(){}
function Child(){}
Child.prototype = Object.create(Parent.prototype);