gpt4 book ai didi

javascript - 如果存在同名的局部变量,如何访问闭包中的变量?

转载 作者:数据小太阳 更新时间:2023-10-29 05:59:27 24 4
gpt4 key购买 nike

我从 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);

///////////////////////

一切正常,但是如果我在内部函数中有一个局部变量与外部函数中的变量同名,那么如何访问该变量?

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);

最佳答案

你不能,因为外部作用域的变量被内部函数的变量覆盖

innerFunction 的范围链看起来像这样:

  innerFunction                     outerFunction             global object ______________________         ________________________        _______________|* someString = 'Hello'| <---- |  someString = 'Hai!'    | <---|* outerFunction| ----------------------        |* content = [HTMLElement]|     |    .....      |                               |* someNum (argument)     |      ---------------                               |* innerFunction          |                                -------------------------* Denotes a resolvable identifier from the scope of innerFunction.

每个函数都有自己的变量对象,函数声明、变量声明和函数形式参数的标识符作为属性存在于此。

这些对象不能通过代码直接访问,作用域链由所有这些链接的对象组成。

当标识符为 resolved 时, 查找在范围链中向上,寻找它的第一次出现,直到到达全局对象,如果找不到标识符,则抛出 ReferenceError

查看以下文章:

关于javascript - 如果存在同名的局部变量,如何访问闭包中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3474504/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com