Immediately invoked function expression: Difference between revisions

Content deleted Content added
Evaluation context: Removed reference to Herman book example. Unless the reader has access to Herman's book or the example from the book, I don't see how the fact that Herman has an example is helpful to the article.
Change "var" to "let" in JavaScript snippets
Line 22:
 
In contexts where an expression is expected, wrapping in parentheses is not necessary:
<syntaxhighlight lang="JavaScriptjavascript">
varlet f = function () { /* ... */ }();
true && function () { /* ... */ }();
0, function () { /* ... */ }();
Line 47:
=== Evaluation context ===
A lack of block scope means that variables defined inside (for example) a [[for loop]] will have their definition "hoisted" to the top of the enclosing function. Evaluating a function that depends on variables modified by the outer function (including by iteration) can be difficult. We can see this without a loop if we update a value between defining and invoking the function.<ref>{{cite web |last=Alman |first=Ben |title=simple-iife-example.js |url=https://gist.github.com/cowboy/4710214 |work=Github |accessdate=5 February 2013}}</ref>
<syntaxhighlight lang="JavaScriptjavascript">
varlet v, getValue;
v = 1;
getValue = function () { return v; };
Line 60:
Hereafter the function passes <code>v</code> as an argument and is invoked immediately, preserving the inner function's execution context.<ref name=JQ>{{cite book |last=Otero |first=Cesar |last2=Larsen |first2=Rob |title=Professional jQuery |year=2012 |publisher=John Wiley & Sons |isbn=978-1-118-22211-9 |page=31}}</ref>
 
<syntaxhighlight lang="JavaScriptjavascript">
varlet v, getValue;
v = 1;
getValue = (function (x) {
Line 72:
 
This is equivalent to the following code:
<syntaxhighlight lang="JavaScriptjavascript">
varlet v, getValue;
v = 1;
function f(x) {
Line 87:
IIFEs are also useful for establishing private methods for accessible functions while still exposing some properties for later use.<ref>{{cite book |last=Rettig |first=Pascal |title=Professional HTML5 Mobile Game Development |year=2012 |publisher=John Wiley & Sons |isbn=978-1-118-30133-3 |page=145}}</ref> The following example comes from Alman's post on IIFEs.<ref name=Alman/>
 
<syntaxhighlight lang="JavaScriptjavascript">
// "counter" is a function that returns an object with properties, which in this case are functions.
varlet counter = (function () {
varlet i = 0;
 
return {