More concise explanation of closures

This commit is contained in:
Adam Brenecki 2013-08-14 17:21:44 +09:30
parent a82859f95b
commit 5f2928df6b

View File

@ -255,24 +255,19 @@ permanent // = 10
// One of JavaScript's most powerful features is closures. If a function is // One of JavaScript's most powerful features is closures. If a function is
// defined inside another function, the inner function has access to all the // defined inside another function, the inner function has access to all the
// outer function's variables. // outer function's variables, even after the outer function exits.
function sayHelloInFiveSeconds(name){ function sayHelloInFiveSeconds(name){
var prompt = "Hello, " + name + "!" var prompt = "Hello, " + name + "!"
function inner(){ function inner(){
alert(prompt) alert(prompt)
} }
setTimeout(inner, 5000) setTimeout(inner, 5000)
// setTimeout is asynchronous, so this function will finish without waiting // setTimeout is asynchronous, so the sayHelloInFiveSeconds function will
// 5 seconds. However, once the 5 seconds is up, inner will still have // exit immediately, and setTimeout will call inner afterwards. However,
// access to the value of prompt. // because inner is "closed over" sayHelloInFiveSeconds, inner still has
// access to the 'prompt' variable when it is finally called.
} }
sayHelloInFiveSeconds("Adam") // will open a popup with "Hello, Adam!" in 5s sayHelloInFiveSeconds("Adam") // will open a popup with "Hello, Adam!" in 5s
// inner() has access to the variable "prompt" strictly because of lexical scope.
// A closure is being demonstrated because the inner() function is being executed
// at a later time, and in fact being executed "outside" the scope where it was
// declared (inside of the implementation of setTimeout()), but yet inner() STILL
// has access to the variable "prompt". It is said that inner() has a "closure"
// over the variables of sayHelloInFiveSeconds().
/////////////////////////////////// ///////////////////////////////////
// 5. More about Objects; Constructors and Prototypes // 5. More about Objects; Constructors and Prototypes