关于js代码的IIFE“立即调用函数表达式”

IIFE是“immediately-invoked function expressions”的缩写,翻译为立即调用函数表达式。

这种技术应用在比较老的js代码当中。

“var” has no block scope

Variables, declared with var, are either function-scoped or global-scoped.In the past, as there was only var, and it has no block-level visibility, programmers invented a way to emulate it. 

简而言之,通过IIFE,来保证var 申明的变量在函数空间中,而不会抢占 全局空间。

 

// Ways to create IIFE

(function() { alert("Parentheses around the function"); })();

(function() { alert("Parentheses around the whole thing"); }());

!function() { alert("Bitwise NOT operator starts the expression"); }();

+function() { alert("Unary plus starts the expression"); }();

设置