javascript - I would like to ask you a question about function promotion in JS?
代言
代言 2017-06-12 09:30:06
0
3
635

The following code:

function a() {
    console.log('1')
}    

(function() {
    console.log(a);
    if(1) {
        function a() {
            console.log('2');
        }
    }
})()

After running, the output is undefined.

After removing the if condition, the output is the second a function

function a() {
    console.log('1')
}    

(function() {
    console.log(a);

    // if(1) {
        function a() {
            console.log(2);
        }
    // }
})()

Knowing that the function has been promoted, in the second piece of code, the second a function will be promoted to before the console.log(a) code, so the second a function is run and output.
But in the first piece of code, I don’t understand why undefined is output.

代言
代言

reply all(3)
代言

Conditional function declarations are processed in the same way as function expressions. Therefore, conditional function declarations lose the hoisting properties of function declarations.

Reference URL: /q/10...

刘奇

When using the function keyword in an if else statement to declare a function, the promotion of variables is different in different browsers. It's just that the declaration of a variable is promoted here, and if else is removed, it becomes a pure function scope.

function a() {
    console.log('1')
}    

(function() {
    var a;
    console.log(a);
    if(1) {
        a = function a() {
            console.log('2');
        }
    }
})()
学习ing

In your IIFE

 if(1) {
  a = function a() {
    console.log('2')
  }
} 

is a function expression, not a function declaration. When the if is removed, it is a function declaration. If is not removed, conosle.log(a), a represents the undefined variable a, refer to https://developer.mozilla.org. ..

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template