我从Google Code Playground获取此信息http://code.google.com/apis/ajax/playground/
/*CLOSURE
* When a function is defined in another function and it
* has access to the outer function's context even after
* the outer function returns
* An important concept to learn in Javascript
*/
function outerFunction(someNum) {
var someString = 'Hai!';
var content = document.getElementById('content');
function innerFunction() {
content.innerHTML = someNum + ': ' + someString;
content = null; // IE memory leak for DOM reference
}
innerFunction();
}
outerFunction(1);
///////////////////////
Run Code Online (Sandbox Code Playgroud)
一切都好,但是如果我在内部函数中有一个局部变量,并且外部函数中的变量同名,那么如何访问该变量?
function outerFunction(someNum) {
var someString = 'Hai!';
var content = document.getElementById('content');
function innerFunction() {
var someString='Hello';
content.innerHTML = someNum + ': ' + someString;
content = null; // IE memory leak for DOM reference
}
innerFunction();
}
outerFunction(1);
Run Code Online (Sandbox Code Playgroud)
你不能,因为外部范围的变量被内部函数的变量所遮蔽.
innerFunction看起来像这样的范围链:
innerFunction outerFunction global object
______________________ ________________________ _______________
|* someString = 'Hello'| <---- | someString = 'Hai!' | <---|* outerFunction|
---------------------- |* content = [HTMLElement]| | ..... |
|* someNum (argument) | ---------------
|* innerFunction |
-------------------------
* Denotes a resolvable identifier from the scope of innerFunction.
每个函数都有自己的变量对象,其中函数声明,变量声明和函数形式参数的标识符作为属性存在.
这些对象不能通过代码直接访问,范围链由所有这些链接对象组成.
当解析标识符时,查找在范围链中上升,查找它的第一次出现,直到到达全局对象,如果未找到标识符,ReferenceError则抛出a.
看看以下文章: