[英]JavaScript code executing after return
在下面的示例中,JavaScript似乎完全忽略了我的return
語句,只是繼續執行代碼。
var x = 1;
(function() {
x = 2;
return;
var x = 3;
})();
console.log(x); // Outputs 1 in both Chrome and FF
當然代碼輸出2
? 如果我從var x = 3
刪除var
關鍵字,它會按預期輸出2
。 這里有一些奇怪的編譯器優化嗎?
不,代碼不應該輸出2,因為變量聲明被提升,所以你的代碼相當於
var x = 1;
(function() {
var x;
x = 2; // changes the internal x variable
return;
x = 3; // does nothing because it's not reached
})();
console.log(x); // Outputs the outside x, which is still 1
這條線
x = 2;
只更改影響外部x
的內部x
變量。
非全局變量的范圍是聲明它的整個函數。 從這個功能的開始到結束。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.