JavaScript提升和范围 [英] JavaScript hoisting and scope

查看:103
本文介绍了JavaScript提升和范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么foo()函数会记录 undefined
第一个 text 变量是一个全局变量,所以 foo()应该有权访问它。

why the foo() function logs undefined? The first text variable is a global variable so foo() should have an access to it.

var text = "outside";

function foo() {
    console.log(text);
    var text = "inside";
}

foo();


推荐答案

即使 var 语句在 console.log()语句之后,声明被提升到函数的开头。所以这声明了一个影响全局变量的局部变量。但是直到你实际上到达语句之后才会进行初始化,这是在 console.log()语句之后。

Even though the var statement is after the console.log() statement, the declaration is hoisted to the beginning of the function. So this declares a local variable that shadows the global variable. But the initialization doesn't happen until you actually get to the statement, which is after the console.log() statement.

所以你的函数相当于:

function foo() {
    var text;
    console.log(text);
    text = 'inside';
}

如果你没有使用 var 声明然后你会继续使用全局变量,直到 console.log()之后才会重新分配。

If you didn't use the var declaration then you would continue to use the global variable, and the reassignment wouldn't happen until after the console.log().

这篇关于JavaScript提升和范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆