gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 16:10:42 28 4
gpt4 key购买 nike

我看到了两种不同的模式和解释。来自 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com