Javascript Pattern Module pattern

The Module pattern encapsulates "privacy", state and organization using closures. It provides a way of wrapping a mix of public and private methods and variables, protecting pieces from leaking into the global scope and accidentally colliding with another developer's interface.
It is a pattern for encapsulation.
the interface can be returned conditionally, giving more freedom than traditional functions



var counter  = ( function(){
	//_count, add, set, get are all private
	var _count = 0;
	
	var add = function(){
		_count++;
	}
	
	var set = function( count ){
		_count = count;
	}
	
	var get = function(){
		return _count;
	}
	//return the interface
	return {
		add: add,
		set: set,
		get: get
	}
})();

counter.add(); //+1
alert( counter.get()); //1
counter.set(23);
alert( counter.get()); //23






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章