apply 與 call 是函式物件上的兩個重要方法。它們都能用來指定函式執行時的 this,差別在於參數傳遞方式。
call 的第一個參數是 this,後續參數需逐一列出。apply 的第一個參數也是 this,第二個參數則是陣列。
function sum(a, b) {
return a + b;
}
console.log(sum.call(window, 10, 20));
console.log(sum.apply(window, [10, 20]));apply 與 call 常見用途之一,是讓函式在不同物件上下文中執行。
window.firstName = 'diz';
window.lastName = 'song';
var person = {
firstName: 'my',
lastName: 'object'
};
function hello() {
console.log(this.firstName + ' ' + this.lastName);
}
hello.call(window);
hello.call(person);透過 call,hello 函式可以分別在 window 與 person 物件上執行,而不需要修改函式本身。
若不使用 call,可能需要把函式動態掛到物件上。
person.hello = hello;
person.hello();這種方式會改變物件結構,而 call 則能直接指定 this,不必新增屬性。
ES5 提供 bind。它會回傳一個新的函式,且 this 被固定為指定物件。
function sayColor() {
console.log(this.color);
}
var obj = { color: 'blue' };
var boundSayColor = sayColor.bind(obj);
boundSayColor();bind 適合用於事件處理函式或回呼函式,能避免 this 指向改變。
此外,函式中若再定義內部函式,內部函式的 this 通常會變成全域物件。若希望保留外層 this,可先用區域變數保存,再透過閉包使用。