Skip to content

Instantly share code, notes, and snippets.

@zD98
Created March 14, 2016 01:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zD98/c0dd53d175180d17e1a5 to your computer and use it in GitHub Desktop.
Save zD98/c0dd53d175180d17e1a5 to your computer and use it in GitHub Desktop.
设计模式

##Module模式

###总结 1. 使用闭包封装私有状态和组织 2. 通过函数作用域模拟私有/公有 ###例子 1. eg: var moudule = (function(jquery,_){ //私有变量 var privateVar = 0; //私有函数 var privateFunc = function(){}

		return {
			//公共变量
			publicVar:"foo",
			//公共函数				
			publicFunc:function(){
				privateVar ++;
				privateFunc();
			}
		}
	})(jQuery, _);
2. eg:
	var revealingModule = funcion(){
		var privateVar,
			publicVar;
		
		function privateFunc(){};
		function publicFunc(){};
		
		return {
			publicVar:publicVar,
			publicFunc:publicFunc
		}

	}();

###分析 1. eg.3 模块 - 优点:支持私有数据, 代码更加整洁 - 缺点:无法为私有成员创建自动化测试, 改变私有方法时, 必须改变与之有关的公有方法 2. eg.4 揭示模块 - 优点:改善可读性 - 缺点:(当私有函数引用共有函数时, 需要打补丁时公有函数不能被覆盖) 不太懂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment