Difference between revisions of "Immediately-invoked function expression"
From Wiki @ Karl Jones dot com
Karl Jones (Talk | contribs) |
Karl Jones (Talk | contribs) |
||
(One intermediate revision by the same user not shown) | |||
Line 1: | Line 1: | ||
− | An '''immediately-invoked function expression''' (or '''IIFE''', pronounced "iffy") is a [[JavaScript]] [[design pattern]] which produces a [[Scope (computer science)|lexical scope]] using JavaScript's [[ | + | An '''immediately-invoked function expression''' (or '''IIFE''', pronounced "iffy") is a [[JavaScript]] [[design pattern]] which produces a [[Scope (computer science)|lexical scope]] using JavaScript's [[Function scope (computer science)|function scoping]]. |
== Description == | == Description == | ||
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 == | ||
+ | * [[Function scope (computer science)]] | ||
* [[JavaScript]] | * [[JavaScript]] | ||
* [[Scope (computer science)]] | * [[Scope (computer science)]] |
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 = {}));