1.预编译前奏
1.imply global暗示全局变量:即任何变量,如果未经声明就赋值此变量归为全局所有。
<script>
a=123;
console.log(a); //123
console.log(window.a) //123
</script>
2.一切声明的全局变量,全是window的属性
<script>
var a=123;
console.log(a); //123
console.log(window.a) //123
</script>
3.函数声明,整体提升(在定义函数的前面调用也可以);
<script>
test()
function test(){
console.log('函数在上面调用能打印')
}
</script>
4.变量声明,声明提升(即只有前面的var text提升了 后半部属于赋值无法提升,所以并不会报错,而是当成了var text 进行的预编译);
<script>
console.log(text); //undefined
var text='abc'
</script>
2.预编译过程
预编译发生在函数执行的前一刻
预编译产生的4个步骤:
1.创建AO
2.找形参和变量声明,将形参名作为AO的属性名,值为undefined
3.将形参实参相统一
4.在函数体里找函数声明,值赋予函数
下面几个例子
function fn(a){
console.log(a); //function a(){}
var a=123;
console.log(a); //123
function a(){};
console.log(a); //123
var b=function(){};
console.log(b); //function(){}
function d(){}; //function d(){}
console.log(d);
}
fn(1);
// 第一次打印 第二次打印第三次打印
// AO{ (2形参和变量声明) (3形参实参相对应) (4函数声明直接提升) (依次赋值)
// a:undefind;-----------------1-------------------function a(){}---------------123
// (第四次打印 )
// b:undefind;---function(){}
// (第五次打印 )
// d:undefind;---function d(){}
// }
//G0{
//a:undefind;
//c:123;
//}
function test(){
console.log(b); //undefind
if(a){
var b=100; //if不成立 a=undefind
}
console.log(b); //undefind
c=123; //AO里找不到 给全局
console.log(c); //123
}
var a;
test();
//AO{
//b:undefind
//}
a=10; //此时a改变了
//G0{
//a:10;
//c:123;
//}
console.log(a); //10
console.log(c); //123
3.
// GO{
// demo:function(){};
// a:100
// f:123
// }
a=100;
function demo(e){
function e(){}
arguments[0]=2;
console.log(e); //2
if(a){ //此时为unefind if语句不成立
var b=123;
}
var c;
a=10;
var a; //10
console.log(b); //unefind
f=123; //给全局
console.log(c); //undefind
console.log(a); //10
}
var a;
demo(1)
//A0{
//e:funcion e(){}; 2
//b:undefind;
//c:undefind;
//a:undefind; 10
//}
console.log(a); //100
console.log(f); //123
看不懂的可以在腾讯课堂上搜索渡一教育的js课,老师讲的挺好,也挺详细。