简体   繁体   English

Javascript内存节省-if语句var声明

[英]Javascript Memory Savings - if Statement var Declarations

Do variables get initialized / stored in memory if they reside in an if statement which doesn't execute, as in the following: 如果变量位于不执行的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');
    }
}

My assumption is no, but Javascript can be a quirky language to say the least. 我的假设不是,但是至少可以说Javascript是一种古怪的语言。 Thanks in advance for your help! 在此先感谢您的帮助!

All var declarations are moved to the top of the function and initialized to undefined. 所有var声明都移至函数顶部,并初始化为undefined。 That is called variable hoisting. 这就是所谓的可变提升。 JavaScript doesn't have block scope, only function and global scope. JavaScript没有块范围,只有函数和全局范围。

Your code is equivalent to the following 您的代码等效于以下代码

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);
    }
}

There is no thing like a block scope in Javascript. Javascript中没有像block scope那样的东西。 See this article . 看到这篇文章 if you want to say so: Javascript has function-scope. 如果您要这样说:Javascript具有功能范围。 So the answer to your question is yes they get initialized. 因此,您的问题的答案是yes它们已初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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