JavaScript 函數有多種調用方式,不同調用方式會影響 this 的指向。理解這些差異,是掌握 JavaScript 物件導向與事件處理的關鍵。
function myFunction(a, b) {
return a * b;
}
myFunction(10, 2);
在瀏覽器中,這類函數通常屬於 window 物件。
const myObject = {
firstName: 'John',
lastName: 'Doe',
fullName: function () {
return this.firstName + ' ' + this.lastName;
}
};
myObject.fullName();
此時 this 指向 myObject。
function MyFunction(arg1, arg2) {
this.firstName = arg1;
this.lastName = arg2;
}
const x = new MyFunction('John', 'Doe');
console.log(x.firstName);
call() 與 apply() 可以改變 this 的指向:
myFunction.call(myObject, 10, 2);
myFunction.apply(myObject, [10, 2]);
兩者差異在於第二個參數:call 接受參數列表,apply 接受陣列。
函數內建 arguments 物件,可取得實際傳入的參數:
function sumAll() {
let sum = 0;
for (let i = 0; i < arguments.length; i += 1) {
sum += arguments[i];
}
return sum;
}
console.log(sumAll(1, 123, 500, 115, 44, 88));
若函數修改物件屬性,通常會影響外部物件;若修改的是原始值參數,則不會影響外部變數。