JS 变量和函数提升 全局变量和局部变量

  • 变量提升

1.

var a = 10;
function test() {
    a = 100;
    console.log(a);
    console.log(this.a);
    var a;
    console.log(a);
}
test();//100  10  100

=>

var a = 10;//全局
function test() {
    var a;//变量提升
    a = 100;//局部
    console.log(a);//局部
    console.log(this.a);//this指向全局window
    console.log(a);//局部
}
test();//100  10  100

2.

var a = 100;
function test() {
    console.log(a);
    var a = 10;
    console.log(a);
}
test();//undefined  10

=>

var a = 100;
function test() {
    var a;//变量提升
    console.log(a);
    a = 10;
    console.log(a);
}
test();//undefined  10

3.

var a = 100;
function test() {
    console.log(a);
    a = 10;
    console.log(a);
}
test();
console.log(a);
//100  10  10

=>

var a = 100;
function test() {
    console.log(a);//全局
    a = 10;//全局
    console.log(a);//全局
}
test();
console.log(a);
//100  10  10
  •  函数提升
console.log(f1); // function f1() {}   
console.log(f2); // undefined  
function f1() { }//函数声明
var f2 = function () { }//函数表达式
    (function (num) {
        var testStr = "test" + num;
        console.log(num);
    })(100);
console.log(testStr);// testStr is not defined
    (function (num) {
        testStr = "test" + num;//不加var,全局变量
        console.log(num);
    })(100);
console.log(testStr);// test100

 

posted @ 2018-11-07 11:37  Chris_在IT道路上前行  阅读(433)  评论(0编辑  收藏  举报