JS函數(shù)中的apply、call、bind理解

函數(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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容