我正在尝试在 codeacademy 上学习 JS,但我无法理解/无法通过这件事。有人可以提供答案并解释为什么会这样吗?将不胜感激。
// This function tries to set foo to be the
// value specified.
function setFoo(val) {
// foo is declared in a function. It is not
// accessible outside of the function.
var foo = val;
}
setFoo(10);
// Now that we are outside the function, foo is
// not defined and the program will crash! Fix this
// by moving the declaration of foo outside of the
// function. Make sure that setFoo will still update
// the value of foo.
alert(foo);
最佳答案
您可以将范围视为一个术语,表示您可以在代码中的特定“级别”访问哪些变量。在 JavaScript 中,这些“级别”由函数定义。每个功能都引入了一个新级别。
例如,拿这个示例代码:
var a;
// you can access a at this level
function function1() {
var b;
// you can access a, b at this level
function function2() {
var c;
// you can access a, b, c at this level
}
}
因此,在您的情况下,您应该在函数外部声明 var foo;
,最好是在函数之上。然后你可以在 setFoo
中用 foo = val;
设置它。 foo
然后引用您在 setFoo
上一层中声明的那个。
foo
可以在 setFoo
和 alert
调用中访问;将其与上面的示例代码进行比较(function1
是 setFoo
,a
是 foo
并且 alert
调用处于最顶层。function2
、b
和 c
未在您的案例中使用。)。
关于javascript - 试图弄清楚范围是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8504461/