变量的生命周期

LIfetime of a variable

我在理解下面全局变量 x 的生命周期时遇到了一些麻烦。我在我不理解的线上评论了我的问题..请帮助...谢谢

var target = document.getElementById("outputArea");
var outString = "";

var x = 0;
var y = 0;

callMeOften2();
callMeOften2();
callMeOften2();
outString += "<br/>";

target.innerHTML = outString;

function callMeOften2() {
    outString += x + "<br/>"; //why isn't this going to give an output of 0? but gave an output of undefined instead? isn't x referring to the global variable x?
    var x = 100;

    x = x + 100;
    outString += "from callMeoften2: " + "x = " + x + "<br/>";
}

以下是所有 Javascript 引擎如何通过变量提升(有效地)处理您的代码

function callMeOften2() {
    var x = undefined;
    outString += x + "<br/>"; //why isn't this going to give an output of 0? but gave an output of undefined instead? isn't x referring to the global variable x?
    x = 100;

    x = x + 100;
    outString += "from callMeoften2: " + "x = " + x + "<br/>";
}

希望对您有所帮助

函数中的 var x 意味着全局 x 是无关紧要的(当然可以在浏览器中使用 window.x 访问,或者在其他 "global" 对象中其他环境)