函數作為對象屬性被調用,this 綁定到該對象。
const obj = {
value: 0,
increment(n) { this.value += n || 1; }
};
obj.increment(); // this → obj
obj.increment(2); // this → obj
函數獨立調用(非對象屬性),this 綁定到全局對象(瀏覽器中為 window)。設計缺陷:內部函數無法直接訪問外部 this。
function foo() { console.log(this); }
foo(); // window
// 經典修復:捕獲外部 this
const obj = {
value: 1,
double() {
const that = this; // 捕獲
function helper() {
that.value *= 2; // 訪問 that
}
helper();
}
};
使用 new 調用函數,創建新對象並綁定 this 到新實例。原型方法中的 this 指向調用實例,而非原型對象。
function Quo(status) {
this.status = status; // this → 新實例
}
Quo.prototype.getStatus = function() {
return this.status; // this → 調用 getStatus 的實例
};
const q = new Quo('confused');
q.getStatus(); // 'confused'
顯式指定 this 值:
func.apply(thisArg, [argsArray]); func.call(thisArg, arg1, arg2...); const bound = func.bind(thisArg);
核心:劫持/借用其他對象的方法,實現繼承或上下文切換。
var test = function() {};
test.prototype = {
foo: "apple",
fun: function() { this.foo = "banana"; }
};
var myTest = new test();
myTest.fun();
console.log(myTest.hasOwnProperty("foo")); // true
console.log(myTest.hasOwnProperty("fun")); // false
解析:
myTest.fun() 為方法調用,this 指向 myTestthis.foo = "banana" 在實例上創建自有屬性 foo,覆蓋原型鏈同名屬性hasOwnProperty("foo") → true(實例自有)fun 定義在原型上,實例無自有 fun → falseclass 內方法默認非綁定,實例調用時自動綁定handler.bind(this) 或箭頭函數屬性 handleClick = () => {}