fonction - Comment fonctionne les fermetures JavaScript

Mots clés : javascriptfunctionvariablesscopeclosuresjavascript

meilleur 5 Réponses fonction - Comment fonctionne les fermetures JavaScript

vote vote

98

function foo() {   const secret = Math.trunc(Math.random()*100)   return function inner() {     console.log(`The secret number is ${secret}.`)   } } const f = foo() // `secret` is not directly accessible from outside `foo` f() // The only way to retrieve `secret`, is to invoke `f`
function Car(manufacturer, model, year, color) {   return {     toString() {       return `${manufacturer} ${model} (${year}, ${color})`     }   } } const car = new Car('Aston Martin','V8 Vantage','2012','Quantum Silver') console.log(car.toString())
function curry(fn) {   const args = []   return function inner(arg) {     if(args.length === fn.length) return fn(...args)     args.push(arg)     return inner   } }  function add(a, b) {   return a + b }  const curriedAdd = curry(add) console.log(curriedAdd(2)(3)()) // 5
const $ = document.querySelector.bind(document) const BACKGROUND_COLOR = 'rgba(200,200,242,1)'  function onClick() {   $('body').style.background = BACKGROUND_COLOR }  $('button').addEventListener('click', onClick)
<button>Set background color</button>
let namespace = {};  (function foo(n) {   let numbers = []   function format(n) {     return Math.trunc(n)   }   function tick() {     numbers.push(Math.random() * 100)   }   function toString() {     return numbers.map(format)   }   n.counter = {     tick,     toString   } }(namespace))  const counter = namespace.counter counter.tick() counter.tick() console.log(counter.toString())
function foo() {   let x = 42   let inner  = function() { console.log(x) }   x = x+1   return inner } var f = foo() f() // logs 43
function createObject() {   let x = 42;   return {     log() { console.log(x) },     increment() { x++ },     update(value) { x = value }   } }  const o = createObject() o.increment() o.log() // 43 o.update(5) o.log() // 5 const p = createObject() p.log() // 42
function foo() {   var result = []   for (var i = 0; i < 3; i++) {     result.push(function inner() { console.log(i) } )   }   return result }  const result = foo() // The following will print `3`, three times... for (var i = 0; i < 3; i++) {   result[i]()  }
vote vote

90

function foo(x) {    var tmp = 3;      function bar(y) {      console.log(x + y + (++tmp)); // will log 16    }      bar(10);  }    foo(2);
function foo(x) {    var tmp = 3;      return function (y) {      console.log(x + y + (++tmp)); // will also log 16    }  }    var bar = foo(2);  bar(10); // 16  bar(10); // 17
var a = 10;    function test() {    console.log(a); // will output 10    console.log(b); // will output 6  }  var b = 6;  test();
vote vote

71

function princess() { 
    var adventures = [];      function princeCharming() { /* ... */ }      var unicorn = { /* ... */ },         dragons = [ /* ... */ ],         squirrel = "Hello!";      /* ... */ 
    return { 
        story: function() {             return adventures[adventures.length - 1];         }     }; } 
var littleGirl = princess(); 
littleGirl.story(); 
vote vote

65

function makeKitchen() {    var trashBags = ['A', 'B', 'C']; // only 3 at first      return {      getTrashBag: function() {        return trashBags.pop();      }    };  }    var kitchen = makeKitchen();    console.log(kitchen.getTrashBag()); // returns trash bag C  console.log(kitchen.getTrashBag()); // returns trash bag B  console.log(kitchen.getTrashBag()); // returns trash bag A
vote vote

60

// Declare counter outside event handler's scope var counter = 0; var element = document.getElementById('button');  element.addEventListener("click", function() {   // Increment outside counter   counter++;    if (counter === 3) {     // Do something every third time     console.log("Third time's the charm!");      // Reset counter     counter = 0;   } });
<button id="button">Click Me!</button>
var element = document.getElementById('button');  element.addEventListener("click", (function() {   // init the count to 0   var count = 0;    return function(e) { // <- This function becomes the click handler     count++; //    and will retain access to the above `count`      if (count === 3) {       // Do something every third time       console.log("Third time's the charm!");        //Reset counter       count = 0;     }   }; })());
<button id="button">Click Me!</button>
//          _______________________Immediately invoked______________________ //         |                                                                | //         |        Scope retained for use      ___Returned as the____      | //         |       only by returned function   |    value of func     |     | //         |             |            |        |                      |     | //         v             v            v        v                      v     v var func = (function() { var a = 'val'; return function() { alert(a); }; })(); 
func();  // Alerts "val" func.a;  // Undefined 

Questions similaires