关于javascript:原型中的函数声明会“污染”原型吗?

Do function declarations in a prototype “pollute” the prototype?

这有什么区别:

1
2
3
4
5
6
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);
}

还有这个:

1
2
3
4
5
6
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; }

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

1
2
3
4
5
6
7
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"污染"了原型:声明调用帮助函数的javascript原型函数的正确方法是什么?

原型中的函数声明会污染原型,而单独分配它们会更干净吗?


原型方法中的函数声明会污染原型吗?

不,因为它们是私人的。

是否将辅助功能分配为构造函数清洁器的方法?

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

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

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

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

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

1
2
3
4
5
6
7
8
9
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;
})();