[英]Javascript Memory Savings - if Statement var Declarations
如果變量位於不執行的if語句中,則變量是否被初始化/存儲在內存中,如下所示:
function blah(){
if(something === true){
var blahOne = 1;
var blahTwo = 2;
var blahThree = 3;
} else {
console.log('The above if statement usually won\'t execute');
}
}
我的假設不是,但是至少可以說Javascript是一種古怪的語言。 在此先感謝您的幫助!
所有var
聲明都移至函數頂部,並初始化為undefined。 這就是所謂的可變提升。 JavaScript沒有塊范圍,只有函數和全局范圍。
您的代碼等效於以下代碼
function blah(){
var blahOne, blahTwo, blahTree;
if(something === true){
blahOne = 1;
blahTwo = 2;
blahThree = 3;
} else {
// blahOne, blahTwo, blahThree are set to undefined
console.log('The above if statement usually won\'t execute');
// But since they have been declared, there's no error in reading them
console.log(blahOne, blahTwo, blahThree);
}
}
Javascript中沒有像block scope
那樣的東西。 看到這篇文章 。 如果您要這樣說:Javascript具有功能范圍。 因此,您的問題的答案是yes
它們已初始化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.