请考虑以下代码
var scope = "global scope";
function checkscope() {
console.log(scope);
var scope = "local scope";
console.log(scope);
}
checkscope();
Run Code Online (Sandbox Code Playgroud)
这将在控制台中打印以下内容
undefined
local scope
Run Code Online (Sandbox Code Playgroud)
为什么第一次console.log
打印undefined
而不是"global scope"
?
这是因为吊装.您的var
关键字是将新的局部scope
变量提升到函数的顶部,这是未定义的.
您的代码与以下内容相同:
function checkscope() {
var scope;
console.log(scope);
scope = "local scope";
console.log(scope);
}
Run Code Online (Sandbox Code Playgroud)
要从scope
函数中访问全局,您必须引用window
用于浏览器的全局对象.如果全局scope
实际上是全局的,而不仅仅是在父范围内,那么这将起作用checkscope()
.
function checkscope() {
console.log(window.scope); // access the global
var scope = "local scope";
console.log(scope);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
33 次 |
最近记录: |