[Medium] 📄 this Binding
1. What is this in JavaScript?
JavaScript 中的
this是什麼?
this 是 JavaScript 中的一個關鍵字,它指向函式執行時的上下文物件。this 的值取決於函式如何被呼叫,而不是在哪裡定義。
this 的綁定規則
JavaScript 中 this 的綁定有四種規則(按優先級從高到低):
- new 綁定:使用
new關鍵字呼叫建構函式 - 顯式綁定:使用
call、apply、bind明確指定this - 隱式綁定:透過物件方法呼叫
- 預設綁定:其他情況下的預設行為
2. Please explain the difference of this in different contexts
請解釋
this在不同情境下的差異
1. 全域環境中的 this
console.log(this); // 瀏覽器:window,Node.js:global
function globalFunction() {
console.log(this); // 非嚴格模式:window/global,嚴格模式:undefined
}
globalFunction();
'use strict';
function strictFunction() {
console.log(this); // undefined
}
strictFunction();
2. 一般函式(Function)中的 this
一般函式的 this 取決於呼叫方式:
function regularFunction() {
console.log(this);
}
// 直接呼叫:this 指向全域物件(非嚴格模式)或 undefined(嚴格模式)
regularFunction(); // window (非嚴格模式) 或 undefined (嚴格模式)
// 作為物件方法呼叫:this 指向該物件
const obj = {
method: regularFunction,
};
obj.method(); // obj
// 使用 call/apply/bind:this 指向指定的物件
const customObj = { name: 'Custom' };
regularFunction.call(customObj); // customObj
3. 箭頭函式(Arrow Function)中的 this
箭頭函式沒有自己的 this