
In most cases, the value of this is determined by how a function is called.
MDN對this的定義是「this在大多數的狀況下,會因為function如何被呼叫,而有所不同」
如過是純粹調用this,那麼this將會指向到全域的window物件上
console.log(this) // 輸出 Window 物件
console.log(this === window); // true
//瀏覽器中window也屬於全域物件
this.a = "AL"
console.log(window.a)
console.log(a)
//都會輸出 AL
另外要特別注意的是,如果在「嚴格模式」下,會自動禁止this指定為全域物件,因此this值預設會是undefined
function f2() {
"use strict";
return this;
}
f2() // undefined
當一個函數作為物件的方法被呼叫時,this 指向該物件
在範例程式碼,getName被呼叫時,它的this會是指向a的物件
const a = {
name: "AL",
getName: function () {
console.log(this.name)
}
}
a.getName() // 輸出 AL
a物件,裡面有name屬性和getName方法,這邊的this.name會訪問到物件中的name屬性this指向當前的物件a.getName被呼叫時,this指向當前的物件a,因此會this.name輸出AL
使用new來調用一個函式時,會建立一個新物件,this將會指到這個新物件上
function a(name){
this.name = name
}
const b = new a("AL")
console.log(b.name) // 輸出 AL
b
AL參數,將它當作新物件name屬性的值,因此b.name會輸出AL
在DOM事件處理中,this通常會指到觸發事件的元素
button.addEventListener('click', function() {
console.log(this); // button element
});
JavaScript ES6 新增的箭頭函數沒有自己的this,箭頭函式的this會由它的外層函式繼承,如果找不到它的外層函式,就會一層層往外找,它會找到全域的this值Window物件
const a = () => this
console.log(a()) // 輸出 Window 物件
call()/apply()/bind()方法直接「指定」this,那麼this將是指定的物件參考文章
鐵人賽:JavaScript 的 this 到底是誰?
JS 核心觀念筆記 - 什麼是 this
MDN-this
Explain.this