learning-javascript
  • Introduction
  • JavaScript ES5 教學
    • 工具準備
    • 流程控制
    • JavaScript 基本特性, 變數
    • Function及Callback function
    • Array及JSON的操作
    • Object, Scope, this
    • ES5中的自訂物件類型-prototype
    • 進階-再講prototype
    • JavaScript重點整理
    • Closure
    • 多個JS檔, module, timer
    • 進階-module pattern
    • 其他
  • 實際應用
    • Server - HTTP request & response
    • Client - 用Fetch跟Server要資料
  • JavaScript ES6 教學
    • 箭頭函數Arrow Function
Powered by GitBook
On this page
  1. JavaScript ES5 教學

Closure

PreviousJavaScript重點整理Next多個JS檔, module, timer

Last updated 7 years ago

其他語言也有closure

可提供類似其他語言的static function-使用static data, 以及跟module pattern結合提供內部private function的空間

Closure使用到的變數的lifetime只要還有人指到這個closure function時,這些變數就會隨著存活.

A closure is a function having access to the parent scope, even after the parent function has closed.

上述link有提到跟 closure相關的 lexical scoping:

the code and see that this works. This is an example of lexical scoping: in JavaScript, the scope of a variable is defined by its location within the source code (it is apparent lexically) and nested functions have access to variables declared in their outer scope.

上述link裡的example, 放在online JB Bin上: 其code:

var add = (function () {
  var counter = 0;
  debugger;  
  return function () {
    counter = counter +1;
    debugger; //用chrome dev tool看, 會看到closure scope
    return counter;  
  };
})();

add();
debugger;
add();
debugger;
add();
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
http://jsbin.com/wurihum/edit?html,js,output