预解析和作用域

预解析:浏览器在解析js代码时,会提前将变量的声明和函数的声明解析到当前作用域的最前面去

 1. 把变量的声明提升到当前作用域的最前面,只会提升声明,不会提升赋值。
 2. 把函数的声明提升到当前作用域的最前面,只会提升声明,不会提升调用。
3. 先提升var,在提升function
4. ` // console.log(num);//undefined
// num = 10;
// console.log(num);//10
//
// f1();//调用f1
//
//
// f2();//报错:预解析将var f2提升到作用域的最前面去,此时并没有给f2赋值为函数
// f2 = function () {
//     console.log("匿名函数");
// };

// var a;
//
// function abc() {
//     var a;
//     alert(a);//undefined
//     a = 10;
// }
//
// a = 25;
//
// abc();


// // // 如果变量和函数同名的话,函数优先
// var a;
// function a() {
//     console.log('aaaaa');
// }
// console.log(a);// 函数体----如果变量和函数同名的话,函数优先
//
// a = 1;
// console.log(a);



// 1、-----------------------------------
// var num;
// function fun() {
//     var num;
//     console.log(num);//undefined
//      num = 20;
// }
//  num = 10;
// fun();



// //2、-----------------------------------
// var a;
// function f1() {
//     var b;
//     // var a;
//     b = 9;
//     console.log(a);//undefined
//     console.log(b);//9
//     a = '123';
// }
// a = 18;
// f1();//调用的时候才会执行函数体内的代码

// 3、-----------------------------------
function f1() {
    var a;//局部变量
    c=9;//隐式全局变量
    b=c;//隐式全局变量
    a=b;
    var a = b = c = 9;
    console.log(a);//9
    console.log(b);//9
    console.log(c);//9
}
f1();
console.log(c);//9
console.log(b);//9
console.log(a);// 报错

`

猜你喜欢

转载自blog.csdn.net/qq_44317018/article/details/88670061
今日推荐