如MDN states闭包用于模拟模块模式的私有(private)方法:
var counter = (function () {
var privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment: function () {
changeBy(1);
},
decrement: function() {
changeBy(-1);
}
};
}());
但是,除了使用模块模式,我们还可以创建一个类。与使用模块模式相比,创建类有什么优点?
function Counter() {
var privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
this.increment = function() {
changeBy(1);
};
this.decrement = function() {
changeBy(-1);
};
}
var counter = new Counter();
最佳答案
What is the advantage of creating a class over using the module pattern?
与使用模块模式相比,创建类的优点是您可以创建一个类的多个实例:
var counter1 = new Counter;
var counter2 = new Counter;
每个实例都有自己的一组私有(private)变量。
另一方面,当您使用模块模式时,您仅创建单个对象(通常称为单例、命名空间或模块)。同样,它有自己的一组私有(private)变量。
模块模式和类都有自己的用途。模块模式对于创建模块、管理器对象(其中必须仅存在一个实例)等很有用。
类模式对于创建相同类型的新数据结构非常有用。例如,链表数据结构将被建模为类,而不是单例或模块。
关于javascript - 使用闭包模拟私有(private)方法与对象中的公共(public)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23064241/