gpt4 book ai didi

javascript - 原型(prototype)中的函数声明 "pollute"是原型(prototype)吗?

转载 作者:行者123 更新时间:2023-11-28 19:57:19 26 4
gpt4 key购买 nike

这有什么区别:

Library1 = function () {};
Library1.prototype.myFunc = function (p) {
function helper1(p) {return p * 2; }
function helper2(p) {return p * 4; }
this.result = helper1(p) + helper2(p);
}

还有这个:

Library2 = function () {};
Library2.prototype.myFunc = function(p) {
this.result = Library2.helper1(p) + Library2.helper2(p);
}
Library2.helper1 = function(p) {return p * 2; }
Library2.helper2 = function(p) {return p * 4; }

无论哪种方式我都会得到相同的结果:

test = new Library1();
test.myFunc(2);
window.console.log(test.result); // 12

test = new Library2();
test.myFunc(2);
window.console.log(test.result); // 12

其中一种方法优于另一种方法吗?

这篇文章暗示方法 1“污染”了原型(prototype):What is the proper way to declare javascript prototype functions calling helper functions

原型(prototype)中的函数声明是否会污染原型(prototype),而单独分配它们在某种程度上更干净?

最佳答案

原型(prototype)方法中的函数声明是否会污染原型(prototype)?

不,因为它们是私有(private)的。

将辅助函数分配为构造函数清洁器的方法吗?

不,因为这样你就会污染构造函数。

其中一种方法优于另一种吗?

如果您不想污染对象,最好在方法内使用函数声明。

这样做的缺点是,每次调用 myFunc 时,都必须重新创建 helper1helper2

然后,如果你不想污染任何东西,也不想每次都重新创建辅助方法,你可以使用

Library1 = (function() {
function Library1() {}
function helper1(p) {return p * 2; }
function helper2(p) {return p * 4; }
Library1.prototype.myFunc = function (p) {
this.result = helper1(p) + helper2(p);
}
return Library1;
})();

关于javascript - 原型(prototype)中的函数声明 "pollute"是原型(prototype)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22314519/

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