Ci-dessous, les différences entre deux révisions de la page.
| Les deux révisions précédentesRévision précédenteProchaine révision | Révision précédente | ||
| 56-tools:javascript [2017/10/18 15:31] – [Closure] Roge | 56-tools:javascript [2018/01/20 02:59] (Version actuelle) – [références] Roge | ||
|---|---|---|---|
| Ligne 11: | Ligne 11: | ||
| [[http:// | [[http:// | ||
| + | http:// | ||
| ===== ES6 ===== | ===== ES6 ===== | ||
| Ligne 122: | Ligne 123: | ||
| </ | </ | ||
| - | Subtil behavour: | + | |
| < | < | ||
| // closure example | // closure example | ||
| + | function makeAdder(x) { | ||
| + | return function(y) { | ||
| + | return x + y; | ||
| + | }; | ||
| + | } | ||
| - | function myContext() { | + | var add5 = makeAdder(5); | 
| - | var x = 0; | + | var add100  | 
| - | function f() { | + | |
| - | x += 1; | + | |
| - | return x; | + | |
| - | }; | + | |
| - | return f; | + | |
| - | }; | + | |
| - | + | ||
| - | // g is now function with closure | + | |
| - | var g1 = myContext(); | + | |
| - | var g2 = myContext(); | + | |
| - | // g maintains a state | + | console.log(add5(2)); // 7 | 
| - | console.log("g1: "+g1());          | + | console.log(add100(2)); // 102 | 
| - | console.log("g2: "+g2());          | + | |
| - | console.log(" | + | |
| </ | </ | ||
| Ligne 392: | Ligne 386: | ||
| [[http:// | [[http:// | ||
| + | [[http:// | ||
| ===== Tests scripts web: jsbin ===== | ===== Tests scripts web: jsbin ===== | ||