1、首先 首先要解釋下,函數體內變數的作用域是在函數定義的時候就確定的,而不是運行時; 函數的上下文是在調用時確定的,函數體內的this指向其上下文; 箭頭函數沒有自己的this,它的this指向的是它上級的this,而它上級的this指向的是上級的上下文。 2、普通函數的this,指向其調用者,箭 ...
1、首先
- 首先要解釋下,函數體內變數的作用域是在函數定義的時候就確定的,而不是運行時;
- 函數的上下文是在調用時確定的,函數體內的this指向其上下文;
- 箭頭函數沒有自己的this,它的this指向的是它上級的this,而它上級的this指向的是上級的上下文。
2、普通函數的this,指向其調用者,箭頭函數this,指向其上級this
let app = {
a: 1,
fn: function () {
console.log('app.fn:', this, this.a);
// this指向需要函數被調用時才能確定,當app.fn()執行,
// 確定其上下文為app,所以this指向app對象
// this.a = app.a = 1
}
}
window.a = 0
let app2 = {
a: 2,
fn: () => {
console.log('app2.fn:', this, this.a);
// app2.fn()執行,上下文為app2,this本應指向app2對象,
// 但是fn是箭頭函數,所以this指向它上級的this,也就是
// 指向app2的this,由於app2的this指向的是其上下文,所以這裡就是window,
// this.a = window.a = 0
}
}
拓展:var、let和const聲明的數據,作用域不同,var聲明的對象可以在global全局作用域下查找,也就是賦值給了window對象;而let和const聲明的對象只能在script作用域下查找,所以window對象上不會顯示聲明的app等對象和函數。var聲明的對象和function函數都可以在global全局作用域下找到。
說到了script,多個script在瀏覽器中一般是分塊編譯的,不是同時編譯。但是作用域只有一個,就是script作用域。
3、seiTimeout中的this,指向window,箭頭函數this,指向其上級this
let app3 = {
a: 3,
fn: function () {
setTimeout(() => {
console.log('app3.fn:', this, this.a);
// app3.fn()執行,但輸出語句在setTimeout中,
// this本應指向window,但箭頭函數的this指向其上級的this,
// 所以this指向fn的this,也就是fn的上下文,this指向app3對象
// this.a = app3.a = 3
}, 1000);
}
}
let app4 = {
a: 4,
fn: ()=> {
setTimeout(() => {
console.log('app4.fn:', this, this.a);
// app4.fn()執行,this本應指向window,
// 但箭頭函數的this指向fn的this,fn的this指向app4的this,
// app4的this指向app4的上下文
// 所以this指向app4的上下文,this指向window
// this.a = window.a = 0
}, 1000);
}
}
let app5 = {
a:5,
fn:function(){
setTimeout(() => {
console.log('app5.fn:', this, this.a);
// app5.fn()執行,this指向fn的this,
// fn的this指向fn的上下文,也就是this指向app5
// this.a = app5.a = 5
}, 1000);
}
}
4、數組中的函數,調用後的this,指向該數組
function app6() {
console.log('app6.fn:', this, this.a);
}
let arr = [0, 1, 2, app6]
arr[3]() // 函數執行,上下文是arr數組,this指向arr,
// this.a = undefined, this[0] = 0