All*_*nde 12

如果在函数中声明带有"var"的变量将是函数的本地变量,否则js引擎将开始在本地范围(函数)中查找变量,如果找不到它,则将在全局空间自动

从以下链接:https://www.inkling.com/read/javascript-definitive-guide-david-flanagan-6th/chapter-3/variable-scope

声明全局JavaScript变量时,实际上要做的是定义全局对象的属性(全局对象).如果使用var来声明变量,则创建的属性是不可配置的(请参阅属性属性),这意味着无法使用delete运算符删除它.

然后,如果您在函数内或全局空间中执行(在任何函数之外):

温度= 10;

你可以在任何地方使用它:

的console.log(window.temp);

只是一堆嵌套函数(从内部函数开始读取代码注释以便更好地理解):

//lots of stuff here but not a "var temp=9"

//I couldn't find "x" I will make it global as a property of the globalObject
 function myFunction(){ //is x here ? no ? then look outside
    (function(){ //is x here ? no ? then look outside
        (function() {  //is x here ? no ? then look outside
                x=5; //declaring x without var, I will look for it
        }());
    }());
}

myFunction();
console.log(window.x); //As x was declared a property from the global object I can do this.
Run Code Online (Sandbox Code Playgroud)

如果你var在一个函数中声明它,如果你在一个函数中window.temp执行它,那么变量将是你的函数的"本地",即:

foo = 1;
function test() {
    var foo = 'bar';
}
test();
alert(foo);

// Result: 1
Run Code Online (Sandbox Code Playgroud)

来自上面的示例和其他人在这里

还要注意在全局空间(外部)中使用"var"所有函数都将创建一个全局变量(窗口对象中的属性) btw,使用var always.