“JavaScript - Penutupan” Kode Jawaban

JavaScript - Penutupan

function makeAdder(x) {
  return function(y) {
    return x + y;
  };
}

var add5 = makeAdder(5);
var add10 = makeAdder(10);

console.log(add5(2));  // 7
console.log(add10(2)); // 12

//=====
//add5 and add10 are both closures. 
//They share the same function body definition, but store different lexical environments. 
//In add5's lexical environment, x is 5, while in the lexical environment for add10, x is 10.
The Arborist

Penutupan dalam JavaScript

var counter = (function() {
  var privateCounter = 0;
  function changeBy(val) {
    privateCounter += val;
  }
  return {
    increment: function() {
      changeBy(1);
    },
    decrement: function() {
      changeBy(-1);
    },
    value: function() {
      return privateCounter;
    }
  };
})();

console.log(counter.value()); // logs 0
counter.increment();
counter.increment();
console.log(counter.value()); // logs 2
counter.decrement();
console.log(counter.value()); // logs 1
Gentle Grouse

Jawaban yang mirip dengan “JavaScript - Penutupan”

Pertanyaan yang mirip dengan “JavaScript - Penutupan”

Lebih banyak jawaban terkait untuk “JavaScript - Penutupan” di JavaScript

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya