函數有3個方法:apply()、call()、bind()。這3個方法都會以指定的this值來調用函數,即會設置調用函數時函數體內this對象的值。apply()方法接收兩個參數:函數內this的值和一個參數數組。第二個參數可以是Array的實例,但也可以是arguments對象。參考以下例子。
window.color = 'red';
let o = {
color: 'blue'
};
function productIntroduction(productName, price) {
console.log(`This product name: ${productName}, ${price} yuan, ${this.color}`);
}
a
function applyProductIntroduction(productName, price) {
productIntroduction.apply(this, arguments);
}
productIntroduction('fingerboard', 100); //This product name: fingerboard, 100 yuan, red
productIntroduction.apply(this, ['mouse', 88]); //This product name: mouse, 88 yuan, red
productIntroduction.apply(window, ['notebook', 6888]); //This product name: notebook, 6888 yuan, red
applyProductIntroduction('water cup', 48); //This product name: water cup, 48 yuan, red
productIntroduction.apply(o, ['iphone 14', 6500]); //This product name: iphone 14, 6500 yuan, blue
apply 的好處是可以將任意對象設置為任意函數的作用域,這樣對象可以不用關心方法。
在使用productIntroduction.apply(o, ['iphone 14', 6500]); 把函數的執行上下文即this切換為對象o之后,結果就變成了顯示"blue"了
call()方法與apply()的作用一樣,只是傳參的形式不同。第一個參數跟apply()一樣,也是this值,而剩下的要傳給被調用函數的參數則是逐個傳遞的。換句話說,通過call()向函數傳參時,必須將參數一個一個地列出來
productIntroduction.call(o,'iphone 14', 6500); //This product name: iphone 14, 6500 yuan, blue
ECMAScript 5出于同樣的目的定義了一個新方法:bind()。bind()方法會創建一個新的函數實例,其this值會被綁定到傳給bind()的對象。比如:
let productBind = productIntroduction.bind(o, 'iphone 14', 6500);
console.info(typeof productBind) // function
productBind() ////This product name: iphone 14, 6500 yuan, blue
可以看到productBind 的類型為function