JavaScript 函數調用時,除顯式參數外隱式傳遞 this 和 arguments。this 綁定在調用時確定(晚綁定),取決於調用模式。
const myObject = {
value: 0,
increment(inc = 1) {
this.value += typeof inc === 'number' ? inc : 1;
return this; // 支持鏈式調用
}
};
myObject.increment(); // this 綁定到 myObject
myObject.increment(2); // value = 3
console.log(myObject.value); // 3
特點:this 指向調用對象,支持鏈式調用,適合面向對象設計。
function add(a, b) {
return a + b;
}
const sum = add(3, 4); // this 綁定到全局對象 (瀏覽器中為 window,嚴格模式為 undefined)
缺陷:內部函數 this 丟失全局對象,ES5 解決方案:
const obj = {
value: 1,
double() {
const helper = () => this.value * 2; // 箭頭函數繼承外層 this
return helper();
}
};
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
return `Hello, ${this.name}`;
};
const person = new Person('Alice'); // this 綁定到新創建對象
console.log(person.greet()); // "Hello, Alice"
原理:new 創建新對象,原型鏈連接到構造函數 prototype,this 指向新對象。
function greet(greeting, punctuation) {
return `${greeting}, ${this.name}${punctuation}`;
}
const user = { name: 'Bob' };
greet.call(user, 'Hi', '!'); // 參數列表
greet.apply(user, ['Hello', '...']); // 參數數組
const bound = greet.bind(user, 'Hey'); // 返回綁定後的新函數
bound('?'); // "Hey, Bob?"
new 構造器調用call/apply/bind 显式綁定obj.method()fn()(默認綁定:全局/undefined)class 語法糖替代構造函數this 上下文this,改用參數傳遞'use strict' 避免默認綁定到全局
const obj = {
value: 42,
getValue: function() {
return this.value;
}
};
const fn = obj.getValue;
console.log(fn()); // undefined (非嚴格模式下 window.value)
const boundFn = obj.getValue.bind(obj);
console.log(boundFn()); // 42