我想知道为什么没有定义范围
function checkscope() {
var scope = "local scope";
function f() {
console.log(scope);
scope = '123' //为什么这里不是全局变量scope,最后结果为什么是scope is not defined
}
return f;
}
var foo = checkscope();
console.log(foo());
console.log(scope)// 结果是scope is not defined
因为您在范围之外定义了它,即函数范围。
请在功能范围之外进行定义。所以无论何时调用函数。范围值将被更改。
var scope;
function checkscope() {
scope = "local scope";
function f() {
console.log(scope);
scope = '123' //为什么这里不是全局变量scope,最后结果为什么是scope is not defined
}
return f;
}
var foo = checkscope();
console.log(foo());
console.log(scope)/
scope
在函数checkscope
中声明。随着}
结束该功能,它将不复存在。
因此,在你使用它的时候,它就不复存在了