javascript 原型(prototype)链 : Rectangle. 原型(prototype) = new Shape() 或 Rectangle.prototype = Shape?

标签 javascript inheritance prototype

我看到了两种不同的模式和解释。来自 DailyJS 和许多其他人的一篇: 矩形.prototype = new Shape();

然后是 Crockford 的 here 这意味着只是 矩形.prototype = 形状;

现在从理论上来说,为什么需要运行"new"?它运行构造函数,是的。它还将矩形的原型(prototype)分配给形状的原型(prototype)。但我们应该能够通过将父级简单地分配到原型(prototype)中来进行继承。

我想知道原因是否是原型(prototype)链。看起来,在情况 1 中,它将创建一个原型(prototype)。这意味着,矩形原型(prototype)将具有形状原型(prototype)。 在第二种情况下,矩形的原型(prototype)将只具有 Shape 的方法,但没有 Shape 的 prototype 方法。

是吗?非常感谢您的任何想法。

最佳答案

Crockford which implies just Rectangle.prototype = Shape;

我实在看不出来。

Now theory-wise, why you need to run the 'new'? it runs the constructor function, yes.

但我们实际上不需要(想要)它,我们只需要从 Shape.prototype 继承

it also assigns the Rectangle's prototype the Shape's prototype.

不是真的。 new Shape 创建一个继承自 Shape.prototype新对象,这才是我们关心的。你说得对。

In the second case, the Rectangle's prototype will just have Shape's methods - but not Shape's prototype methods.

是的,没错。您应该从 Shape.prototype 继承 - 但通过 Object.create(Shape.prototype) 继承,而不是通过创建实例。请参阅JavaScript inheritance: Object.create vs newWhat is the reason [not] to use the 'new' keyword here? 。这就是 Crockford 实际所做的 - 甚至在 EcmaScript 5.1 引入 Object.create 之前,他就找到了一种巧妙的方法来使用他的辅助函数来做到这一点

function object(o) {
    function F() {}
    F.prototype = o;
    return new F();
}

现在,它是 native 不支持 Object.create 的浏览器中的常用填充程序。

关于javascript 原型(prototype)链 : Rectangle. 原型(prototype) = new Shape() 或 Rectangle.prototype = Shape?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13089250/

相关文章:

javascript - 如何在 xtify 中配置无声警报

javascript - jQuery.remove() 真的是同步的吗?

c++:需要正确的语法以避免 MISRA 14-6-1 警告。具有依赖基类的类模板

c++ - '{' token 错误之前的预期类名

c++ - 如何强制派生类比较

javascript - Script Src 正在破坏页面

javascript - Edge 中的 blob 损害了 HTTPS 安全性

javascript - 将函数原型(prototype)设置为新对象

javascript - javascript中如何通过prototype实现super机制?

ruby-on-rails - 将 onClick 事件附加到 Rails 的 link_to_function