javascript - variable scope issue
伊谢尔伦
伊谢尔伦 2017-05-19 10:07:17
0
2
396
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?

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(2)
刘奇

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);
}
})()
曾经蜡笔没有小新

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);
    }
})();
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!