Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

exercise - 声明提升 #6

Open
meahu opened this issue Apr 27, 2019 · 1 comment
Open

exercise - 声明提升 #6

meahu opened this issue Apr 27, 2019 · 1 comment

Comments

@meahu
Copy link
Owner

meahu commented Apr 27, 2019

exercise - 声明提升

@meahu
Copy link
Owner Author

meahu commented Apr 27, 2019

if(true)、if(false) 里的声明会提升

先看变量的:

console.log(a);
if (false) {
    var a = 1;
}
console.log(a);

// 结果:
undefined
undefined

再看

console.log(a);
if (true) { // 这里为 true 了
    var a = 1;
}
console.log(a);

// 结果:
undefined
1 // true,当然执行了

函数的:

console.log(fn);
if (false) {
    function fn() {};
}
console.log(fn);

// 结果:
undefined
undefined

函数的:

console.log(fn);
if (true) { // 这里为 true 了
    function fn() {};
}
console.log(fn);

// 结果:
undefined
ƒ fn() {} // true,当然执行了

但是这种情况下函数只是声明的提升,函数体并没有提升。

练习练习

console.log(fn); // 执行结果是?

function fn() {
    console.log("fn");
}
if (true) {
    function fn () {
        console.log("fn1");
    }
} else {
    function fn() {
        console.log("fn2");
    }
}
init();
function fn() {
    console.log("fn");
}
        
function init() {
    fn(); // 执行结果是?
    if (false) {
        function fn() {
            console.log("fn2");
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant