简体   繁体   中英

Why the second console.log() gives 2, insted of 1?

Why the second console.log() gives 2 , insted of 1 ?

 function f() { console.log(2); } f(); (function() { f(); f = function() { console.log(1); } })(); 

In javascript function declarations are hoisted within enclosing scopes, but assignments are not. What you have in your second call is not a function declaration — you are just changing the value of an existing variable. If you wanted a hoisted version of f() in your second call you would need to do something like:

 function f() { console.log(2); } f(); (function() { f(); function f() { // this is a function declaration so it will be hoisted to the top console.log(1); } })(); 

You are calling f(); in the IIFE before your function expression. If you move your second f(); call below the expression you will get the result you are expecting.

function f() {
    console.log(2);
}

f();

(function() {
    f = function() {
        console.log(1);
    }
    f();
})();

The second "console.log(1)" outputs 2 because it is really the first "console.log(2)" that you are calling — twice. You never actually called the function that would trigger "console.log(1)". Here's a more representative example of what is happening:

 function f(value) { console.log(value); } f('a'); (function() { f('b'); f = function() { console.log('c'); } // unless you call "f()" at this point, this would not work. The "f = func ... " doesn't get hoisted. })(); 

Notice how the output is "a" and "b", but "c" is never logged. Variable assignments of functions don't get hoisted, I'm assuming that you would thought would happen?

Hope that helps.

That is because the function declaration is getting executed twice.

FYI - function declaration gets hoisted but function expression does not.

 function f() { // function declaration console.log(2); } f(); // 2 (function() { f(); // 2 f = function() { // function expression console.log(1); } // you can use function expression here now that it is defined f(); // 1 })(); // will output: // 2 // 2 // 1 

Read up:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM