Content deleted Content added
→Examples: Explain this section with a code example. |
m Added additional way to pass variables into IIFE |
||
(2 intermediate revisions by 2 users not shown) | |||
Line 21:
Passing variables into the scope is done as follows:
<syntaxhighlight lang="
(function(a, b) { /* ... */ })("hello", "world");
(function(a="hello", b="world") { /* ... */ })(); //also works
</syntaxhighlight>
Line 36 ⟶ 37:
==Examples==
The key to understanding design patterns such as IIFE is to realize that prior to ES6, JavaScript only featured [[Scope (computer science)#Function scope|function scope]] (thus lacking [[Scope (computer science)#Block scope|block scope]]), passing [[Call_by_reference|values by reference]] inside [[Closure (computer science)|closure]]s.<ref>{{cite book |last=Haverbeke |first=Marijn |title=Eloquent JavaScript |year=2011 |publisher=No Starch Press |isbn=978-1-59327-282-1 |pages=29–30}}</ref> This is no longer the case, as the ES6 version of JavaScript implements block scoping using the new <code>let</code> and <code>const</code> keywords.<ref>{{cite web |last1=Orendorff |first1=Jason |title=ES6 In Depth: let and const |url=https://hacks.mozilla.org/2015/07/es6-in-depth-let-and-const/ |website=Mozilla Hacks – the Web developer blog |publisher=[[Mozilla]] |access-date=16 October 2024 |date=31 Jul 2015}}</ref><syntaxhighlight lang="javascript">
// Before ES6:
var foo = 1;
var bar = 2;
Line 45 ⟶ 46:
console.log(foo, bar); // 1 4
// Since ES6:
const foo = 1;
let bar = 2;
|