若果裡面沒return 的話;
什麼是閉包(closure function )
Two one sentence summaries:
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!).
上面這個例子,變一下, 傳回出來。!!
The simplest example of a closure is this:
When a JavaScript function is invoked, a new execution context is created. Together with the function arguments and the parent object, this execution context also receives all the variables declared outside of it (in the above example, both 'a' and 'b').
It is possible to create more than one closure function, either by returning a list of them or by setting them to global variables. All of these will refer to the same <code>x</code> and the same <code>tmp</code>, they don't make their own copies.
Here the number <code>x</code> is a literal number. As with other literals in JavaScript, when <code>foo</code> is called, the number <code>x</code> is copied into <code>foo</code> as its argument <code>x</code>.
On the other hand, JavaScript always uses references when dealing with objects. If say, you called <code>foo</code> with an object, the closure it returns will reference that original object!
As expected, each call to <code>bar(10)</code> will increment <code>x.memb</code>. What might not be expected, is that <code>x</code> is simply referring to the same object as the <code>age</code> variable! After a couple of calls to <code>bar</code>, <code>age.memb</code> will be 2! This referencing is the basis for memory leaks with HTML objects.