如果声明和变量提升 [英] If statement and variable hoisting

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

问题描述

我正在学习JavaScript中的变量提升,并发现这种行为很奇怪:

I am learning about variable hoisting in JavaScript, and found this behavior weird:

var x = 0;

(function () {
    //Variable declaration from the if statement is hoisted:
    //var x; //undefined

    console.log(x); //undefined

    if (x === undefined) {
        var x = 1; //This statement jumps to the top of the function in form of a variable declaration, and makes the condition become true.
    }
}());

这是否正确,在这种情况下,语句使条件成立,以便可以执行?

Is it correct, that in this case, the statement makes the condition true so it can be executed?

推荐答案

仅提升提升声明,但不提升任务。您的代码相当于:

Hoisting hoists only the declaration, but not the assignment. Your code is equivalent to:

var x = 0;

(function () {
    //Variable declaration from the if statement is hoisted:
    var x;

    console.log(x); //undefined

    if (x === undefined) {
        x = 1;
    }
}());

if语句的条件表达式求值为 true 到达 x = 1

The if statement's condition expression evaluates to true and x = 1 is reached.

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

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