这有什么区别:
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“污染”了原型:声明调用辅助函数的 javascript 原型函数的正确方法是什么。
原型中的函数声明是否会污染原型,而单独分配它们在某种程度上更干净?
原型方法中的函数声明会污染原型吗?
不,因为它们是私人的。
是否将辅助函数指定为构造函数清理器的方法?
不,因为这样你会污染构造函数。
其中一种方法优于另一种吗?
如果你不想污染对象,最好在方法内使用函数声明。
这样做的缺点是,每次调用
myFunc
时,都必须重新创建 helper1
和 helper2
。
然后,如果你不想污染任何东西,也不想每次都重新创建辅助方法,你可以使用
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;
})();