2013年11月28日

有關 Closures

(Purpose)Stackoverflow 上面有人問Closures 的目的
  •   Data Encapsulation
  •   The purpose is persistence of local scope


(Long Description)網路上種種描述啥咪是 Closures
  •   A closure is a function defined within another scope that has access to all the variables within the outer scope.
  •   A closure is an inner function that has access to the outer (enclosing) function’s variables scope chain.
  •   A closure is the local variables for a function - kept alive after the function has returned, or
  •   A closure is a stack-frame which is not deallocated when the function returns. (as if a 'stack-frame' were malloc'ed instead of being on the stack!)


(Master says) 大師是這麼說的
Crockford says, is simply:
* An inner function always has access to the vars and parameters of its outer function, even after the outer function has returned…

這概念

簡單的說,就是 Javascript 的 private member,讓外面的function可以拿到 function 內部的local variable.也是就物件導向裡面封裝的概念

稍微複雜一點的來說,由於Javascript variable scope 的特性, 在每一個 function scope 裡面的variable,只會活在 function 內部,如果單存使用 getter(), setter() 去讀取跟寫入一個private member, 怎麼讓原本只會活在 function 內部的 local variable,讓外面的世界可以存取.

專業的說法,請參考下列的文章,有些要看到範例才會有感覺.



下面有一些參考資訊,可以由上而下來閱讀(個人覺得由簡單到困難)

其中,簡體中文的那個參考,由於個人的簡體閱讀障礙,閱讀的過程有些難以理解某些名詞

所以放在最後


Reference :

Understand JavaScript Closures With Ease

Why use "closure"?

javascript closure advantages?

Identifier Resolution and Closures in the JavaScript Scope Chain

Private Members in JavaScript

深入理解JavaScript闭包(closure)