變數提升與函式提升
變數宣告提升
- 通過var定義(宣告)的變數--在定義陳述句之前就可以訪問到
- 值為undefined
console.log(a); //undefined
var a = 1;
//執行順序
var a;
console.log(a);
a = 1;
函式宣告提升
- 通過function宣告的函式--在之前就可以直接呼叫
- 值為函式定義(物件)
fn();//可呼叫
function fn(){
conse.log('哈哈');
}
執行背景關系
代碼分類--位置
全域代碼
函式(區域)代碼
全域執行背景關系
-
在執行全域代碼前將window確定為全域執行背景關系
- 對全域資料進行預處理
- var定義的全域變數-->undefined--添加為window的屬性
- function宣告的全域函式-->賦值--添加為window的方法
- this-->賦值window
- 開始執行全域代碼
//全域執行背景關系 console.log(a1, window.a1); //undefined undefined a2(); //a2(); console.log(this); //window var a1 = 3; function a2() { console.log('a2()'); } console.log(a1);
函式執行背景關系
-
在呼叫函式--準備執行函式體之前--創建對應的函式執行背景關系物件--虛擬的,存在于堆疊中
- 對區域資料進行預處理
- 形參變數-->賦值(實參)--添加為執行背景關系的屬性
- arguments-->賦值(實參串列)--添加為執行背景關系的屬性
- var定義的區域變數-->underfined--添加為執行背景關系的屬性
- this-->賦值(呼叫函式的物件)
- 開始執行函式體代碼
//函式執行背景關系 function fn(a1) { console.log(a1); //2 console.log(a2); //undefined a3(); //a3 console.log(this); //window console.log(arguments); //2,3 var a2 = 4; function a3() { console.log('a3'); } } fn(2, 3);
執行背景關系堆疊
- 在全域代碼執行前--JS引擎會創建一個堆疊來存盤管理所有的執行背景關系物件
- 在全域執行背景關系(window)確定后--將其添加到堆疊中(壓堆疊)
- 在函式執行背景關系創建后--將其添加到堆疊中(壓堆疊)
- 在當前函式執行完后--將堆疊頂的物件移除(出堆疊)
- 當所有代碼執行完成后--堆疊中只剩下window
<script>
//執行全域背景關系
var a = 10;
var bar = function (x) {
var b = 5;
foo(x + b); //進入foo執行背景關系
}
var foo = function (y) {
var c = 5;
console.log(a + c + y);
}
bar(10); //進入bar函式執行背景關系
</script>

面試題
console.log('gb:' + i);
var i = 1;
foo(1);
function foo(i) {
if (i == 4) {
return;
};
console.log('fb:' + i);
foo(i + 1);
console.log('fe:' + i);
}
console.log('ge:' + i);

function a(){};
var a;
console.log(a); //f a(){}--變數先被提升--函式覆寫變數后提升
if(!(b in window)){
var b = 1;
}
console.log(b); //undefined--變數先被提升為全域變數
var c = 1;
function c(c){
var c = 3;
}
c(2); //報錯--變數先被提升--函式后被提升--變數最后被賦值--因此不是函式,不能被呼叫
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/550702.html
標籤:JavaScript
上一篇:JavaScript 簡寫語法
下一篇:返回列表
