Created
April 24, 2014 07:47
-
-
Save shengoo/11245444 to your computer and use it in GitHub Desktop.
JavaScript module pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//自执行函数(immediately invoked function) | |
(function(){ | |
}()); | |
//这样也可以(this works too) | |
(function(){})(); | |
//增加参数(add params to first) | |
(function(my){ | |
}(variable)); | |
//增加返回值(add return) | |
(function(my){// | |
return my; | |
}(variable)); | |
//这样MODULE就是返回的my(give my to MODULE) | |
//js加载完就会运行这个函数,并且把返回值赋予MODULE | |
var MODULE = (function(my){// | |
return my; | |
}(variable)); | |
//把自执行函数的参数换成返回的变量(change immediately invoked function parameter) | |
var MODULE = (function(my){// | |
return my; | |
}(MODULE || {})); | |
//你可以在其他任意地方这样定义MODULE | |
//所有的方法都会可以用MODULE来调用 | |
//now you can define MODULE anywhere you like, | |
//all the functions inside will be extended to others | |
// 增加功能(add capabilities) | |
var MODULE = (function (my) { | |
//you cannot access inner variable | |
var variable = {}; | |
// this is inner function, you cannot call it outside of the MODULE | |
function innerFun(){ | |
console.log(variable);//you can access inner variable here | |
} | |
//this function will be exported, you can call it outside | |
my.someFun = function(){ | |
//you can call inner variable and function here | |
console.log(variable); | |
innerFun(); | |
}; | |
return my; | |
}(MODULE || {})); | |
//MODULE || {} is the parameter passed to this MODULE, | |
//equals "my" inside MODULE | |
//you can define MODULE anywhere else |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment