【问题标题】:js inheritance and prototype assignmentjs继承和原型赋值
【发布时间】: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


【解决方案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); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-06
    • 1970-01-01
    • 2022-10-13
    • 2013-05-20
    • 1970-01-01
    • 2015-03-30
    • 2013-07-17
    相关资源
    最近更新 更多