在javascript中的闭包中重新定义变量之前访问变量

Dam*_*aux 3 javascript

请考虑以下代码

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"

MrC*_*ode 6

这是因为吊装.您的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)