我有一些函数和变量:
function b() {
myvar = 1;
console.log(myvar);
a();
}
myvar = 5;
a();
b();
a();
function a() {
console.log(myvar);
}
控制台日志输出为:5, 1, 1, 1
。为什么最后一个 a() 调用得到“1”作为输出而不是“5”?因为我认为 a() 是从全局上下文中调用的,并且该全局上下文将 myvar=5 作为其外部(上一级)变量?
最佳答案
此代码中没有本地变量 - 每个变量名称引用都是对全局变量的引用,因此每当发生重新分配时,都会重新分配该全局变量。
如果b
重新分配了一个名为myvar
的本地变量,那么你是正确的,例如,如果myvar
在 b
中是一个参数,或者在 b
中用 var/let/const
声明:
function b() {
// next line has "var",
// indicating that whenever the following variable name is used inside this function
// it'll be referring to a local variable, not the global `myvar`:
var myvar = 1;
console.log(myvar);
a();
}
myvar = 5;
a();
b();
a();
function a() {
console.log(myvar);
}
关于Javascript 函数作用域和执行上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54173985/