js继承和原型赋值

时间:2015-01-27 13:58:55

标签: javascript oop inheritance prototype

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

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

1 个答案:

答案 0 :(得分:1)

这是第一个例子中的原因:

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

但是

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

所以这是错误的用法.... 正确的方法是采用下一种方式:

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