Javascript-可变提升 [英] Javascript- Variable Hoisting

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

问题描述

这是一个简单的片段,我只是不明白。

This is a simple snippet, I just dont understand something.

下面的代码输出12,我明白了,因为 var foo = 12; 替换先前的变量声明。

The below code outputs 12, I understand that, because the var foo = 12; replaces the previous declaration of the variable.

<script>
var foo = 1;
function bar(){
  if (!foo) {
    var foo = 12;
  }
  alert(foo);
}
bar();
</script>

在下面的代码中,它会提醒 1 ,这意味着声明的变量函数内部可以访问该函数。

In the below code, it alerts 1 , which means the variable declared outside the function is accessible inside the function.

  <script>
    var foo = 1;
    function bar(){
      alert(foo);
    }
    bar();
    </script>

但是,在下面的代码中,为什么它会提示未定义?我想,它会提醒 1 ,我只是将之前声明的变量分配给新的。

But, in the below code, why it alerts undefined ?? I thought, it will alert 1, I am just assigning the previously declared variable to the new one.

  <script>
    var foo = 1;
    function bar(){
      if (!foo) {
        var foo = foo;
      }
      alert(foo);
    }
    bar();
    </script>


推荐答案

变量声明被推送到函数的开头。

Variable declarations are pushed to the start of the function.

因此实际上会发生以下情况:

Therefore in reality the following is happening:

function bar(){
      var foo;
      if (!foo) {
        foo = foo;
      }
      alert(foo);
}

因此您需要将此更改为使用窗口.foo 这样你就是指全局属性而不是函数的属性:

Therefore you would need to change this to use window.foo so that you're referring to the global property rather than the function's property:

var foo = 1;
function bar(){
   var foo;
   if (!window.foo) {
      foo = window.foo;
   }
   alert(foo);
}
bar();

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

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