Module模式

在JavaScript中,Module模式用于进一步模拟类的概念,通过这种方式,能够使一个单独的对象拥有共有/私有方法和变量,从而屏蔽来自全局作用域的特殊部分。产生的结果是:函数名与在页面上其他脚本定义的函数冲突的可能性降低。

Module模式使用闭包封装“私有”状态和组织。它提供了一种包装混合公有/私有方法和变量的方式,防止其泄露至全局作用域,并与别的开发人员的接口发生冲突。通过该模式,只需返回一个公有的API,而其他的一切则都维持在私有闭包里。

example:

var testModule = (function() {
	var counter = 0;
	return {
		incrementCounter: function() {
			return ++counter;
		},
		resetCounter: function() {
			console.log("counter value prior to reset: " + counter);
			counter = 0;
		}
	};
})();

//用法
testModule.incrementCounter();
testModule.resetCounter();