`
mybwu_com
  • 浏览: 178623 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

IIFE (immediate-invoke function expression ) in javascript

 
阅读更多
IIFE(Immediate invoke function expression)


sometime , we hope to define and invoke a function immediately .for this case , can have several ways to do .


(function(){ /* code */ }()); // recommanded



(function(){ /* code */ })(); // But this one works just as well



// Because the point of the parens or coercing operators is to disambiguate
// between function expressions and function declarations, they can be
// omitted when the parser already expects an expression (but please see the
// "important note" below).

var i = function(){ return 10; }();
true && function(){ /* code */ }();
0, function(){ /* code */ }();




// If you don't care about the return value, or the possibility of making
// your code slightly harder to read, you can save a byte by just prefixing
// the function with a unary operator.



!function(){ /* code */ }();

~function(){ /* code */ }();

-function(){ /* code */ }();

+function(){ /* code */ }();
 

new function(){ /* code */ }
new function(){ /* code */ }() // Only need parens if passing arguments





now introducing the module- pattern in JS :




// Create an anonymous function expression that gets invoked immediately,
// and assign its *return value* to a variable. This approach "cuts out the
// middleman" of the named `makeWhatever` function reference.
//
// As explained in the above "important note," even though parens are not
// required around this function expression, they should still be used as a
// matter of convention to help clarify that the variable is being set to
// the function's *result* and not the function itself.

var counter = (function(){
var i = 0;

return {

get: function(){

return i;

},

set: function( val ){

i = val;

},


increment: function() {

return ++i;

}


};


}());







// `counter` is an object with properties, which in this case happen to be
// methods.


counter.get(); // 0
counter.set( 3 );
counter.increment(); // 4
counter.increment(); // 5



counter.i; // undefined (`i` is not a property of the returned object)

i; // ReferenceError: i is not defined (it only exists inside the closure)




The Module Pattern approach is not only incredibly powerful, but incredibly simple. With very little code, you can effectively namespace related methods and properties, organizing entire modules of code in a way that both minimizes global scope pollution and creates privacy.


reference : http://benalman.com/news/2010/11/immediately-invoked-function-expression/
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics