作用域变量 var

var没有块级作用域,定义后在当前闭包中都可以访问,如果变量名重复,就会覆盖前面定义的变量,并且也有可能被其他人更改。

变量名重复,就会覆盖前面定义的变量,并且也有可能被其他人更改:

console.log(a);

function  a() {
    console.log(1)
}
function  a() {
    console.log(2)
}

输出 :  2 

定义后在当前闭包中都可以访问

if (true) {
    var a = "a"; // 期望a是某一个值
}
console.log(a);

输出:   a

var在for循环标记变量共享,一般在循环中使用的i会被共享,其本质上也是由于没有块级作用域造成的

for (var i = 0; i < 10; i++) {
    setTimeout(function () {
        alert(i);
    }, 0);
}
弹窗 10 次
原文地址:https://www.cnblogs.com/guangzhou11/p/11325573.html