search

Home  >  Q&A  >  body text

javascript - variable scope issue

var name = 'World!';
(function () {
    if (typeof name === 'undefined') {
        var name = 'Jack';
        console.log('Goodbye ' + name);
    } else {
        console.log('Hello ' + name);
    }
})();

Excuse me, name is a global variable. Why is it undefined in the immediate execution function?

伊谢尔伦伊谢尔伦2802 days ago461

reply all(2)I'll reply

  • 怪我咯

    怪我咯2017-05-19 10:09:17

    Because there is also a name variable in your self-executing function. The variable name in the self-executing function is declared with var and will be promoted to the top of the scope of the self-executing function
    That is, your code can be roughly viewed as executed like this

    (function () {
    //最新执行
    var name
    //然后执行if
    if (typeof name === 'undefined') {
        //然后在这里给name赋值
        name = 'Jack';
        console.log('Goodbye ' + name);
    } else {
        console.log('Hello ' + name);
    }
    })()

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-19 10:09:17

    Pay attention to variable promotion, your code will become as follows after parsing

    var name ;
    name = 'World!';
    (function () {
        var name;
        if (typeof name === 'undefined') {
            name = 'Jack';
            console.log('Goodbye ' + name);
        } else {
            console.log('Hello ' + name);
        }
    })();

    reply
    0
  • Cancelreply