这些块的JS范围如何工作? [英] How does the JS scope of these blocks work?

查看:92
本文介绍了这些块的JS范围如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以解释为什么以下产生1,2而另一产生5?它们不应该同时产生5吗?

Can anyone explain why the following produces 1,2 and the other produces 5? Should they not both produce 5?

//produces 1,2
(function () {

    var a = [5];

    function bar() {
        if (!a) {
          var a = [1, 2];
        }
        console.log(a.join());
    }

    bar();

})();

基于阅读一些关于JS闭包的文章,我希望它们都能产生5.看起来不行在任何地方找到一篇文章,可以提供一些有关第一个块产生的原因的见解。

Based on reading some articles about JS closure, I expect them both to produce 5. Can't seem to find an article anywhere that would give some insight as to why the first block produces otherwise.

//produces 5
(function () {

    var a = [5];

    function bar() {
        if (a) {
          console.log(a.join());
        }
        else {
          console.log([1, 2].join())
        }
    }

    bar();

})();

谢谢!

推荐答案

由于javascripts var hoisting ,此代码:

Due to javascripts var hoisting, this code:

(function () {
    var a = [5];
    function bar() {
        if (!a) {
          var a = [1, 2];
        }
        console.log(a.join());
    }
    bar();
})();

相当于此代码:

(function () {
    var a = [5];
    function bar() {
        var a; // a === undefined at this point
        if (!a) {
          a = [1, 2];
        }
        console.log(a.join());
    }
    bar();
})();

所以你可以看到, a 确实会当测试if条件时, falsey (即!= === true)

So you can see, a will indeed be falsey (i.e. !a === true) when the if condition is tested

这篇关于这些块的JS范围如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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