JavaScript 闭包的例子

例子一:

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>

例子二:

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

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

发布了188 篇原创文章 · 获赞 88 · 访问量 58万+

猜你喜欢

转载自blog.csdn.net/henryhu712/article/details/104027658