好好認識一下 JavaScript 中的 this 用法

Milo Chen
4 min readNov 12, 2023

--

在寫 JavaScript 語言的時候, this 到底是指到哪邊去呢?

this 這個關鍵字在 JavaScript 語言中是很複雜的觀念,它與一般程式語言的 this 不太一樣,它的 this 代表的是什麼仍是取決於它的使用情境 context.

Global Context

global execution context 中,也就是任何函數之外,this 在 strict mode 或是 non-strict mode 都是參考到 global object. 在瀏覽器中這個global object 就是指 window, 而 Node.JS 中就是指 global

如果你在 browser 中呼叫 console.log(this),得到的會是 [object Window], 而在 NodeJS 中得到的將會是 [object global]

Function Context

function testfunc() {
console.log(this);
}
testfunc();

總之, this 是誰,就要看誰 call testfunc()

上面這個程式如果是在 global context 呼叫的話,this 會是 global object, 舉例NodeJS來說在 strict mode 下會印出 undefined 而 non-strict mode 則是印出 [object global]. 舉browser 來說 strict mode 下會印出 undefined 而 non-strict mode 則是印出 [object Window]

再來看下面這個例子,使用 `function() {…}` 跟 `() => {…}` 兩者的不同

let myobj = {
attr: "AttrB"
testfunc: function() {
console.log(this.attr);
}
}
obj.testfunc(); // 印出"AttrB"
//這邊的 this 就是看是誰call testfunc()的,this 就是誰
let myobj = {
attr: "AttrB"
testfunc: () => {
console.log(this.attr);
}
}
obj.testfunc(); // 印出"undefined"
//這邊的 this 就不是指 obj了

使用箭頭 () => {…} 的這個版本並沒有自己的 this. 因此它取到的 this 是創選時繼承parent scope而來的. 所以說在箭頭這版本的情況下, 換句話說,在第2個例子中,this 所指的不是誰call它的,而是取決於程式這個 lexical 下的 context (靜態的)。

Event Handler Context

mybtn.addEventListener('click', function() {
console.log(this); // 印出整個 mybtn 的 HTML
});

在 Event Handler 這個 Context 下 this 指東西是 event listener 所附加的那個 element 上,也就是 event.currentTarget ,以這個為例,event listener 所附加的元素為 mybtn, 因此你打印 this 的時候,便會將這個 mybtn 整個 HTML 給印出來啦

以上初學是比較常見的東西,會需要知道,當然還有以下三個 Constructor Context, Class Context 以及 Explicit / Implicit Binding 的情況。但這邊就不再多說,如果有興趣想知道更詳營的讀者們,可以按 Clap 給這篇文章拍拍手,如果有很多人想進一步知道的話,我就再寫下去 :D , 不然的話應該對於大部份來玩玩開發的人來說,目前這樣子就應該夠了

Constructor Context

Class Context

Explicit / Implicit Binding

--

--

Milo Chen
Milo Chen

Written by Milo Chen

Study in Law/CS/EE & Dev in blockchain, AI, IoT, mobile app. Good in almost programming language with github https://github.com/milochen0418. 永遠十八歲/對世界好奇/INFP型

No responses yet