在下面的示例中,我试图访问函数 outer 中的 x
。
我期望得到 20 作为输出,但是输出是 undefined
。
谁能解释为什么会这样,有没有办法访问外部 x?
var x = 10;
function outer() {
var x = 20;
function inner() {
var x = 30;
function printX() {
console.log(outer.x);
}
printX();
}
inner();
}
outer();
最佳答案
作用域在 JavaScript 中并不是这样设计的。为了将变量 x 附加到它的作用域,您需要通过名称或此引用来引用该作用域的对象。
在您的示例中发生的事情是您对 printX 的调用尝试记录附加到函数 outer 的变量 x。函数派生自 JavaScript 中的对象,因此它们可能具有附加到它们的属性,因此您不会给您一个引用错误,而是未定义,因为变量不存在。
有关范围界定的更多信息,请参阅我的 answer on scope in JavaScript .
var x = 10; // Globally scoped variable named "x"
function outer() {
var x = 20; // Locally scoped to outer function variable named "x"
// in outer function, this variable takes precedence over the
// globally scoped x which was 10
function inner() {
var x = 30; // Locally scoped to inner function variable named "x"
// in inner function, this variable takes precedence over the
// parent scoped x which was 20
function printX() {
console.log(outer.x); // Tries to read "x" property of the outer function
// If this had been console.log(x) it would give 30 because it is scoped to the function inner's variable environment
}
printX();
}
inner();
}
outer();
至于接下来要做什么,这实际上取决于最终目标是什么。解决这个问题的简单方法是,正如此处评论中所指出的那样,简单地重命名变量。但是,这仍然不能解决尝试通过属性名称而不是变量名称访问变量的主要问题。为了按名称访问变量,只需使用它的名称(如果它们共享范围,则区分名称),而不是尝试访问在这种情况下不存在的属性名称。
关于javascript - 如何从 JavaScript 中的外部范围访问变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52212632/