[英]Why the second console.log() gives 2, insted of 1?
為什么第二個console.log()
給出2
,則為1
?
function f() { console.log(2); } f(); (function() { f(); f = function() { console.log(1); } })();
在javascript中,函數聲明懸掛在封閉范圍內,但分配沒有。 第二個調用中的內容不是函數聲明-您只是在更改現有變量的值。 如果您想在第二個調用中使用f()
的提升版本,則需要執行以下操作:
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); } })();
您正在呼叫f(); 在函數表達之前的IIFE中。 如果移動第二個f(); 在表達式下方調用,您將獲得期望的結果。
function f() {
console.log(2);
}
f();
(function() {
f = function() {
console.log(1);
}
f();
})();
第二個“ console.log(1)”輸出2,因為它實際上是您正在調用的第一個“ console.log(2)”-兩次。 您從未真正調用過會觸發“ console.log(1)”的函數。 這是正在發生的事情的更具代表性的示例:
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. })();
注意輸出如何為“ a”和“ b”,但從未記錄“ c”。 函數的變量分配不會被取消,我假設您會認為會發生?
希望能有所幫助。
那是因為函數聲明被執行了兩次。
僅供參考-函數聲明被吊起,但函數表達式沒有被吊起。
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
閱讀:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.