クロージャーの例はJavaScript

例1:

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>

例2:

var func = (function() { var a = 'val'; return function() { alert(a); }; })();

https://stackoverflow.com/a/15097817/3054511

彼は188元記事に公開 ウォン称賛88 ビュー580 000 +を

おすすめ

転載: blog.csdn.net/henryhu712/article/details/104027658