預編譯
簡單理解記憶
- 函數聲明整體提升 系統會把函數提升到邏輯的最前面
- 變量 聲明提升
這兩句話不能解決的問題
console.log(a);
function a(a) {
var a = 234;
var a = function () {
}
a();
}
var a = 123;
未經聲明的變量歸window所有
- imply global暗示全局變量:即任何變量,如果
變量未經聲明就賦值,此變量就爲全局對象所有。
eg:a= 123;eg: var a=b= 123; - -切聲明的全局變量,全是window的屬性。window就是全局的域
eg:var a = 123; ===> window.a = 123;
預編譯過程 發生在函數執行的前一刻
1.創建AO對象:執行期上下文
2找形參和變量聲明,將變量和形參名作爲AO
屬性名,值爲undefined
3.將實參值和形參統一
4.在函數體裏面找函數聲明,值賦予函數體
例子1:
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() {}
Fn(1);
預編譯過程:AO{
a:function a () {}
b:undefined,
d:function d() {}
}
例子2
function test(a, b) {
console.log(a) ;//1
C=0;
var C;
a=3;
b=2;
console.log(b) ;//2
function b () {}
I
function d ( )
{}
console.log(b) ;//2
test(1);
例子3
function test(a, b) {
console.log(a) ;//function a () {}
console.log(b);//undefined
var b = 234;
console.log(b);//234
a = 123;
console.log(a);//123
function a () {}
var a;
b = 234;
var b = function ( ){}
console.log(a);//123
console.log(b) ;|//function () {}
}
test(1);
AO {
a:function
b:1
}
有全局的執行期上下文的時候
console.log(test);//function text () { }
function test(test) {
console.log(test) ;//function text () { }
var test = 234;
console.log(test);//234
function test( ){
}
}
test(1) ;
var test = 123;
過程 :
在全局的執行期上下文:
GO {
text :function text () { }
}
函數執行的執行上下文
AO {
}
複雜的面試題例子:
function test() {
console.log(b);//undefined
if (a) {
var b = 100;
}
console.log(b)//undefined
c = 234;
console.log(c);//234
}
var a;
test();
// AO{
// b: undefined
// }
a = 10;
console.log (b);//Uncaught ReferenceError: b is not defined
console.log(c);//234
tip:>(免費獲取最新完整前端課程關注vx公衆號:前端拓路者coder,回覆:資料
如果這個文章對你有用的話,歡迎點贊轉發關注,讓更多的小夥伴看到呀,畢竟分享是一個程序員最基本的美德!!!
如果有不對的請大佬指教)