Difference between revisions of "Immediately-invoked function expression"

From Wiki @ Karl Jones dot com
Jump to: navigation, search
 
Line 10: Line 10:
  
 
This pattern has been referred to as a '''self-executing anonymous function'''; [[Ben Alman]] introduced "IIFE" as a more semantically accurate term for the pattern, shortly after its discussion arose on comp.lang.javascript.
 
This pattern has been referred to as a '''self-executing anonymous function'''; [[Ben Alman]] introduced "IIFE" as a more semantically accurate term for the pattern, shortly after its discussion arose on comp.lang.javascript.
 +
 +
== Code sample ==
 +
 +
<pre>
 +
(function(app) {
 +
})(window.app || (window.app = {}));
 +
</pre>
  
 
== See also ==
 
== See also ==

Latest revision as of 16:52, 9 December 2016

An immediately-invoked function expression (or IIFE, pronounced "iffy") is a JavaScript design pattern which produces a lexical scope using JavaScript's function scoping.

Description

Immediately-invoked function expressions can be used to:

  • Avoid variable hoisting from within blocks
  • Protect against polluting the global environment
  • Simultaneously allow public access to methods while retaining privacy for variables defined within the function

This pattern has been referred to as a self-executing anonymous function; Ben Alman introduced "IIFE" as a more semantically accurate term for the pattern, shortly after its discussion arose on comp.lang.javascript.

Code sample

(function(app) {
})(window.app || (window.app = {}));

See also

External links