Immediately invoked function expression: Difference between revisions

Content deleted Content added
m Examples: style, punct.
Line 39:
 
==Examples==
The key to understanding design patterns such as immediately-invoked function expressions is to realize that JavaScript has [[Scope (computer science)#Function scope|function scope]] (but not [[Scope (computer science)#Block scope|block scope]]) and passes values by reference inside a [[Closure (computer science)|closure]].<ref>{{cite book|last=Haverbeke|first=Marijn|title=Eloquent JavaScript|year=2011|publisher=No Starch Press|isbn=9781593272821|pages=29–30}}</ref> (This is no longer entirely true, in the latest version of JavaScript block scoping does exist thanks to the new <code>let</code> keyword.<ref>ECMAScript 6 — New Features: Overview & Comparison, [http://es6-features.org/#BlockScopedVariables Block-Scoped Variables].</ref>)
 
===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 whichthat 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="JavaScript">
var v, getValue;
Line 80:
</syntaxhighlight>
 
David Herman's ''Effective JavaScript'' contains an example illustrating the problems of evaluation context inside loops.<ref>{{cite book|last=Herman|first=David|title=Effective Javascript|year=2012|publisher=Addison-Wesley|isbn=9780321812186|pages=44–45}}</ref> While Herman's example is deliberately convoluted, it arises directly from the same lack of block scope.<ref>{{cite book|last=Zakas|first=Nicholas C.|title=Professional JavaScript for Web Developers|chapter=Mimicking Block Scope|year=2011|publisher=John Wiley & Sons|isbn=9781118233092}}</ref>
 
===Establishing private variables and accessors===
Line 110:
</syntaxhighlight>
 
If we attempt to access <code>counter.i</code> from the global environment, it will be undefined, as it is enclosed within the invoked function and is not a property of <code>counter</code>. Likewise, if we attempt to access <code>i</code>, it will result in an error, as we have not declared <code>i</code> in the global environment.
 
==Terminology==