Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

第9题(2019-08-01): 请写出以下代码的输出结果: #3

Open
qappleh opened this issue Aug 1, 2019 · 1 comment
Open
Labels

Comments

@qappleh
Copy link
Owner

qappleh commented Aug 1, 2019

var name = 'Tom';
(function() {
    if (typeof name == 'undefined') {
        var name = 'Jack';
        console.log('Goodbye ' + name);
    } else {
        console.log('Hello ' + name);
    }
})();  
@qappleh qappleh changed the title 2019-08-01(第9题): 请写出以下代码的输出结果: 第9题(2019-08-01): 请写出以下代码的输出结果: Aug 1, 2019
@qappleh
Copy link
Owner Author

qappleh commented Aug 2, 2019

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

解析:var 声明的变量没有块作用域,IIFE内的var穿透了块作用域,变量会提升到最近的 function 作用域的上层,但此时只是声明了变量,并没有赋值,到实际运行了赋值语句之后才有值,在之前值为 undefined

@qappleh qappleh added the 京东 label Aug 20, 2019
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant