'悬挂'JavaScript变量 [英] 'Hoisted' JavaScript Variables

查看:96
本文介绍了'悬挂'JavaScript变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不完全理解为什么以下显示悬挂到最后。

I do not fully understand why the following displays "hoisted" towards the end.

var x = 'set';
var y = function () 
{
    // WHAT YOU DON'T SEE -> var x; 
    // is effectively "hoisted" to this line!

    if (!x) 
    { 
        // You might expect the variable to be populated at this point...it is not
        // though, so this block executes
        var x = 'hoisted'; 
    }

    alert(x); 
}

//... and this call causes an alert to display "hoisted"
y();

任何指针都会受到赞赏。

Any pointers would be appreciated.

推荐答案

在<$上引用 MDN文档c $ c> var 吊装


因为变量声明(以及声明中的声明)在执行任何代码之前处理,在代码中的任何地方声明变量等同于在顶部声明它。这也意味着变量可以在声明之前使用。这种行为称为提升,因为看起来变量声明被移动到函数或全局代码的顶部。

Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it's declared. This behavior is called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code.

所以,在你的情况下,JavaScript知道一个局部变量(不是在外面声明的那个) x 是在函数的某个地方定义的,但它确实在执行到达分配给 x 的赋值语句之前,不知道它的实际值。 (声明在编译期间处理,分配在执行时间内完成)直到分配完成,将使用默认值 undefined 。由于 undefined 是假的,因此

So, in your case, JavaScript knows that a local variable (not the one declared outside) x is defined somewhere in the function, but it does not know the actual value of it until the execution reaches an assignment statement which assigns to x. (Declarations are processed during the compile time and assigments are done in the execution time) Till the assignment is done, the default value undefined will be used. Since undefined is falsy, the condition

if (!x) {

$ b满足
$ b

并执行赋值语句。这就是你在警告框中获得悬挂的原因。

假设你没有在函数内声明 x

Let's say you have not declared x inside the function,

var x;

var y = function () {
    if (!x) {
        x = 'hoisted';
    }
    alert(x);
}

y();
alert(x);

此处,因为 x 未在任何地方声明在函数内,在运行时,JavaScript将在更高的范围内查找 x 。在这种情况下,它在函数外部找到它。因此,将使用 x 。由于您已将已提升分配给 x ,因此内部提醒将还说悬挂,在离开该功能后, alert(x)也会提醒悬挂

Here, since x is not declared anywhere within the function, at runtime, JavaScript will look for x in the higher scopes. In this case, it finds it right outside the function. So, that x will be used. Since you assigned hoisted to x, the inner alert will also say hoisted and after leaving the function, alert(x) will also alert hoisted.

这篇关于'悬挂'JavaScript变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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