“penutupan” Kode Jawaban

penutupan

var counter = (function() {  //exposed function references private state (the outer function’s scope / lexical environment) after outer returns. 
 var privateCounter = 0;
 function changeBy(val)   { privateCounter += val; }
 return {  increment: function() {changeBy(1); },
           decrement: function() {changeBy(-1);},
           value: function() {return privateCounter; }
  };
})();

counter.increment(); counter.increment();
counter.decrement();
counter.value();      //  1
Pink Person

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

penutupan

func main() {
  x := 0
  increment := func() int {
    x++
    return x
  }
  fmt.Println(increment())
  fmt.Println(increment())
}
Careful Cardinal

penutupan

function add(a) {
     return function(b) {
         return a + b;
     };
 }

 let addTen = add(10);
 let addSeven = addTen(7);

 console.log(addSeven); // 17
Gleaming Grasshopper

penutupan

function makeFunction() {
  const name = 'TK';
  function displayName() {
    console.log(name);
  }
  return displayName;
};
Sreyansh Sahay

penutupan

def say():
    greeting = 'Hello'

    def display():
        print(greeting)

    display()
Code language: Python (python)
lohani

Jawaban yang mirip dengan “penutupan”

Pertanyaan yang mirip dengan “penutupan”

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya