gpt4 book ai didi

Javascript:覆盖函数的原型(prototype) - 不好的做法?

转载 作者:行者123 更新时间:2023-12-03 02:07:29 26 4
gpt4 key购买 nike

由于当我们声明一个函数时,我们得到它的原型(prototype)的构造函数属性指向该函数本身,因此像这样覆盖函数的原型(prototype)是一个不好的做法吗:

function LolCat() {
}

// at this point LolCat.prototype.constructor === LolCat

LolCat.prototype = {
hello: function () {
alert('meow!');
}
// other method declarations go here as well
};

// But now LolCat.prototype.constructor no longer points to LolCat function itself

var cat = new LolCat();

cat.hello(); // alerts 'meow!', as expected

cat instanceof LolCat // returns true, as expected

这不是我的做法,我还是更喜欢下面的方法

LolCat.prototype.hello = function () { ... }

但我经常看到其他人这样做。

那么,为了方便起见,如第一个示例所示,通过覆盖函数的原型(prototype)对象来从原型(prototype)中删除构造函数引用是否有任何影响或缺点?

最佳答案

我看不到任何人提到这方面的最佳实践,所以我认为这取决于您是否可以看到 constructor 属性曾经有用。

值得注意的是,constructor 属性(如果您不销毁它)也将在创建的对象上可用。在我看来这可能很有用:

var ClassOne = function() {alert("created one");}
var ClassTwo = function() {alert("created two");}

ClassOne.prototype.aProperty = "hello world"; // preserve constructor
ClassTwo.prototype = {aProperty: "hello world"}; // destroy constructor

var objectOne = new ClassOne(); // alerts "created one"
var objectTwo = new ClassTwo(); // alerts "created two"

objectOne.constructor(); // alerts "created one" again
objectTwo.constructor(); // creates and returns an empty object instance

所以在我看来这是一个架构决定。您是否希望允许创建的对象在实例化后重新调用其构造函数?如果是的话就保存下来吧。如果没有,就销毁它。

请注意,objectTwo 的构造函数现在完全等于标准对象构造函数 - 无用。

objectTwo.constructor === Object; // true

因此调用new objectTwo.constructor()相当于new Object()

关于Javascript:覆盖函数的原型(prototype) - 不好的做法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12260375/

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