〖學習筆記〗JavaScript — this
3 min readJul 18, 2021
Depends on how the function is called. the JavaScript
this
keyword refers to the object it belongs to.
每一個 function 在被執行的時候都會有一個 reference 指向所屬的環境,這就是 this,有四種函數調用方法:
- 一般函數調用(In normal function calls) :
this
被綁定到全局對象。 - 方法調用(Within methods on objects) :
this
指向呼叫他的對象。 - 建構函數調用(Within an object that has been constructed) : 函數或者方法調用之前帶有
new
,this
指向執行完的新對象。 - 隱式/間接調用(A function invoked with .call, .apply, or bind) :
this
可以指定給任何對象。
this 代表什麼呢?
function test() {
console.log(this)
}// 答案是不知道,因為 this 取決于執行這個 function 時的環境
function 執行時所屬的物件(誰呼叫他,this 就暫時屬他),而不是 function 本身。預設綁定 this 為全域物件,也就是 window。
- 這個 function 是被 new 出來的嗎?如果是,那 this 就是這個被建構出來的物件
- 這個 function 是以 .call() 或 .apply() 的方式呼叫的嗎?如果是,那 this 就是被指定的物件
- 這個 function 是透過 .bind() 指定或是本身是「箭頭函式」?如果是,那 this 就是被指定的物件
- 這個 function 被呼叫時,是否存在於某個物件?如果是,那 this 就是那個物件
- 如果沒有滿足以上條件,那 this 就一定是全域物件,在嚴格模式下則是
undefined
。 Ex: function 有 ajax 的請求
/* Within an object that has been constructed */
var b = new a();
// 這時 this 會是 a 這個 function 所產生的 object/* A function invoked with .call, .apply, or bind */
a.call(obj);
// 這時 this 也是 obj/* Within methods on objects */
var obj = {};
obj.a = a;
obj.a(); // 這時 this 就是 obj/* In normal function calls */
a(); // this 就是 window
可透過另一個變數對目前 this 做參考
let that = this ;
資料來源: