函數(shù)有3個(gè)方法:apply()、call()、bind()。這3個(gè)方法都會(huì)以指定的this值來(lái)調(diào)用函數(shù),即會(huì)設(shè)置調(diào)用函數(shù)時(shí)函數(shù)體內(nèi)this對(duì)象的值。apply()方法接收兩個(gè)參數(shù):函數(shù)內(nèi)this的值和一個(gè)參數(shù)數(shù)組。第二個(gè)參數(shù)可以是Array的實(shí)例,但也可以是arguments對(duì)象。參考以下例子。
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 的好處是可以將任意對(duì)象設(shè)置為任意函數(shù)的作用域,這樣對(duì)象可以不用關(guān)心方法。
在使用productIntroduction.apply(o, ['iphone 14', 6500]); 把函數(shù)的執(zhí)行上下文即this切換為對(duì)象o之后,結(jié)果就變成了顯示"blue"了
call()方法與apply()的作用一樣,只是傳參的形式不同。第一個(gè)參數(shù)跟apply()一樣,也是this值,而剩下的要傳給被調(diào)用函數(shù)的參數(shù)則是逐個(gè)傳遞的。換句話說(shuō),通過(guò)call()向函數(shù)傳參時(shí),必須將參數(shù)一個(gè)一個(gè)地列出來(lái)
productIntroduction.call(o,'iphone 14', 6500); //This product name: iphone 14, 6500 yuan, blue
ECMAScript 5出于同樣的目的定義了一個(gè)新方法:bind()。bind()方法會(huì)創(chuàng)建一個(gè)新的函數(shù)實(shí)例,其this值會(huì)被綁定到傳給bind()的對(duì)象。比如:
let productBind = productIntroduction.bind(o, 'iphone 14', 6500);
console.info(typeof productBind) // function
productBind() ////This product name: iphone 14, 6500 yuan, blue
可以看到productBind 的類型為function