gpt4 book ai didi

JavaScript 对象 : is it not OK to redefine the prototype?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:34:50 26 4
gpt4 key购买 nike

<分区>

我注意到 MDN他们说:“不推荐重新定义原型(prototype)”,他们给出了重新定义原型(prototype)的示例,以及如何通过附加到现有原型(prototype)而不是重新定义原型(prototype)来更好地实现原型(prototype)的示例。 p>

我特别想知道这一点,因为在其他情况下我们需要重新定义原型(prototype):

Cube.prototype = Object.create(....)
Manager.prototype = new Employee;

是不是 MDN 说你不应该像他们给出的例子(如下所示)那样重新定义原型(prototype),但实际上像我上​​面提到的那样重新定义它是可以的?

这里(转述)是他们在 MDN 上所说的话页:

//MDN says this is not the best way since it redefines the prototype

function MyObject(name, message) {
this.name = name.toString();
this.message = message.toString();
}
MyObject.prototype = {
getName: function() {
return this.name;
},
getMessage: function() {
return this.message;
}
};

//MDN says this is better to do it this way since this does not
//redefine the prototype:

function MyObject(name, message) {
this.name = name.toString();
this.message = message.toString();
}
MyObject.prototype.getName = function() {
return this.name;
};
MyObject.prototype.getMessage = function() {
return this.message;
};

我的问题:这是否正确?如果正确,您能否提供一些幕后细节来回答原因。特别是查看 MDN 示例——为什么一种方法实际上比另一种方法更好?

一个简短的说明:我喜欢 MDN 并感谢该站点上的所有工作!我上面的评论只是一个问题,所以我可以理解重新定义原型(prototype)的规则,而不是以任何方式批评他们所说的。

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