【发布时间】:2015-01-27 13:58:55
【问题描述】:
我正在学习 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
他们声称原型分配是错误的,我不明白为什么?
【问题讨论】:
-
试试看 mdn 关于instanceof,当你分配原型时,在第二种情况下,你没有得到 B 继承 A 你得到 B 和 A 继承自其他一些
-
第二行有语法错误。你的意思是
A.prototype.doSomething = function(){}? -
@pawel 你是对的,我已经更正了,谢谢!
-
执行
B.prototype = A.prototype;你将拥有((new B() instanceof A) == true和((new A()) instanceof B) == true,正如Grundy 建议的那样。您发布的网站在 instanceof 测试中失败,原因是Ninja.prototype = { dance: Person.prototype.dance };这会破坏原型链。 -
它打破了它,因为 Ninja.prototype = { dance: Person.prototype.dance };是将通用对象重新分配到原型中并覆盖分配
标签: javascript oop inheritance prototype