http://benalman.com/news/2010/11/immediately-invoked-function-expression/
// Because this function returns another function that has access to the // "private" var i, the returned function is, effectively, "privileged." function makeCounter() { // `i` is only accessible inside `makeCounter`. var i = 0; return function() { console.log( ++i ); }; } // Note that `counter` and `counter2` each have their own scoped `i`. var counter = makeCounter(); counter(); // logs: 1 counter(); // logs: 2 var counter2 = makeCounter(); counter2(); // logs: 1 counter2(); // logs: 2 i; // ReferenceError: i is not defined (it only exists inside makeCounter)
Immediately-Invoked Function Expression (IIFE)
Fortunately, the SyntaxError “fix” is simple. The most widely accepted way to tell the parser to expect a function expression is just to wrap in in parens, because in JavaScript, parens can’t contain statements. At this point, when the parser encounters the function
keyword, it knows to parse it as a function expression and not a function declaration.
// Either of the following two patterns can be used to immediately invoke // a function expression, utilizing the function's execution context to // create "privacy." (function(){ /* code */ }()); // Crockford recommends this one (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 */ }(); // Here's another variation, from @kuvos - I'm not sure of the performance // implications, if any, of using the `new` keyword, but it works. // http://twitter.com/kuvos/status/18209252090847232 new function(){ /* code */ } new function(){ /* code */ }() // Only need parens if passing arguments
Saving state with closures
Just like when arguments may be passed when functions are invoked by their named identifier, they may also be passed when immediately invoking a function expression. And because any function defined inside another function can access the outer function’s passed-in arguments and variables (this relationship is known as a closure), an Immediately-Invoked Function Expression can be used to “lock in” values and effectively save state.
// This doesn't work like you might think, because the value of `i` never // gets locked in. Instead, every link, when clicked (well after the loop // has finished executing), alerts the total number of elements, because // that's what the value of `i` actually is at that point. var elems = document.getElementsByTagName( 'a' ); for ( var i = 0; i < elems.length; i++ ) { elems[ i ].addEventListener( 'click', function(e){ e.preventDefault(); alert( 'I am link #' + i ); }, 'false' ); } // This works, because inside the IIFE, the value of `i` is locked in as // `lockedInIndex`. After the loop has finished executing, even though the // value of `i` is the total number of elements, inside the IIFE the value // of `lockedInIndex` is whatever the value passed into it (`i`) was when // the function expression was invoked, so when a link is clicked, the // correct value is alerted. var elems = document.getElementsByTagName( 'a' ); for ( var i = 0; i < elems.length; i++ ) { (function( lockedInIndex ){ elems[ i ].addEventListener( 'click', function(e){ e.preventDefault(); alert( 'I am link #' + lockedInIndex ); }, 'false' ); })( i ); } // You could also use an IIFE like this, encompassing (and returning) only // the click handler function, and not the entire `addEventListener` // assignment. Either way, while both examples lock in the value using an // IIFE, I find the previous example to be more readable. var elems = document.getElementsByTagName( 'a' ); for ( var i = 0; i < elems.length; i++ ) { elems[ i ].addEventListener( 'click', (function( lockedInIndex ){ return function(e){ e.preventDefault(); alert( 'I am link #' + lockedInIndex ); }; })( i ), 'false' ); }
相关推荐
( function(){…} )()和( function (){…} () )是两种javascript立即执行函数的常见写法,最初我以为是一个括号包裹匿名函数,再在后面加个括号调用函数,最后达到函数定义后立即执行的目的,后来发现加括号的原因...
立即执行函数(IIFE)是JavaScript编程中一个非常实用的概念,它允许开发者创建一个独立的作用域,其中定义的变量不会影响到全局作用域,同时也不会被外部访问。在深入解析IIFE之前,我们需要了解JavaScript中函数的...
在JavaScript编程中,立即执行函数(Immediately Invoked Function Expression,简称IIFE)是一种常见的模式,用于创建一个独立的作用域。这样做可以避免变量污染全局作用域,同时能立即执行其中的代码。IIFE可以有...
在Javascript中,任何function在执行的时候都会创建一个执行上下文,因为为function声明的变量和function有可能只在该function内部,这个上下文,在调用function的时候,提供了一种简单的方式来创建自由变量或私有子...
### JavaScript自执行函数之伪命名空间封装法 #### 一、引言 在现代Web开发中,JavaScript作为一种广泛使用的客户端脚本语言,其作用日益显著。为了提高代码的可维护性和安全性,开发者们不断探索新的编码技巧。...
JavaScript中的立刻执行函数,也称为立即调用的函数表达式(IIFE,Immediately Invoked Function Expression),是一种在JavaScript中创建私有作用域和确保代码立即执行的常见技术。它的核心在于利用函数表达式来...
( function(){…} )()和( function (){…} () )是两种javascript立即执行函数的常见写法,最初我以为是一个括号包裹匿名函数,再在后面加个括号调用函数,最后达到函数定义后立即执行的目的,后来发现加括号的原因...
3. **立即执行**:如果你希望定义一个函数并立即执行它,可以使用函数表达式结合立即执行函数表达式(Immediately Invoked Function Expression,IIFE)的方式。 #### 立即执行函数表达式(Immediately Invoked ...
立即执行函数表达式(IIFE,全拼为Immediately Invoked Function Expression),是JavaScript中一种特殊且非常实用的模式。IIFE的主要作用是创建一个独立的作用域,从而避免全局变量污染,增强代码模块化,以及实现...
JavaScript中的自执行函数是一种常见的编程技巧,用于创建独立的、封闭的作用域,避免全局变量污染。自执行函数的格式通常是`(function(args) { ... })(params)`,它会立即执行括号内的函数,并传递`params`作为参数...
- **自调用函数**:立即执行的函数,通常用于创建私有作用域或执行初始化任务。 - **内部函数**:在另一个函数内部定义的函数,可以访问外部函数的变量。 - **返回函数的函数**:函数可以返回另一个函数,这种模式常...
- 立即执行函数表达式(Immediately Invoked Function Expression,IIFE)是一种常用的模式,它可以在定义时立即执行。 ```javascript (function() { alert(1); })(); ``` - 这种模式可以有效地避免全局变量...
如果省略了函数名,就创建了一个匿名函数,例如用在回调或立即调用的函数表达式(IIFE)。 二、函数参数 JavaScript函数可以接受任意数量的参数,即使在声明时未指定。例如: ```javascript function greet(name) {...
JavaScript中的一个独特特性是立即执行函数表达式(IIFE),它允许代码块在定义后立即执行,而不是将其赋给变量或函数名。这种技术在编写模块化代码、创建闭包以及避免全局变量污染方面非常有用。 立即执行函数...