JavaScript 中階
請解釋 JavaScript 中 this 的值?
概述
this 是 JavaScript 中一個特殊的關鍵字,它的值不是在定義時決定,而是在執行時根據呼叫方式決定(箭頭函式除外)。
五種綁定規則
1. 預設綁定(Default Binding)
在非嚴格模式下,this 指向全域物件(瀏覽器中為 window,Node.js 中為 global)。嚴格模式下為 undefined。
function show() {
console.log(this); // window(非嚴格模式)
}
show();
2. 隱式綁定(Implicit Binding)
作為物件的方法呼叫時,this 指向該物件。
const obj = {
name: 'Alice',
greet() {
console.log(this.name); // 'Alice'
}
};
obj.greet();
3. 顯式綁定(Explicit Binding)
使用 call、apply、bind 手動指定 this。
function greet() {
console.log(this.name);
}
greet.call({ name: 'Bob' }); // 'Bob'
greet.apply({ name: 'Carol' }); // 'Carol'
const greetDave = greet.bind({ name: 'Dave' });
greetDave(); // 'Dave'
4. new 綁定
使用 new 呼叫建構函式時,this 指向新建立的物件。
function Person(name) {
this.name = name;
}
const p = new Person('Eve');
console.log(p.name); // 'Eve'
5. 箭頭函式(Lexical Binding)
箭頭函式沒有自己的 this,繼承外層作用域的 this,且不受 call/apply/bind 影響。
const obj = {
name: 'Frank',
greet: function() {
const inner = () => console.log(this.name);
inner(); // 'Frank'(繼承 greet 的 this)
}
};
obj.greet();
優先順序
new 綁定 > 顯式綁定 > 隱式綁定 > 預設綁定
✦ AI 模擬面試
輸入你的答案,AI 即時分析精準度與改進空間
登入後即可使用 AI 評分
