關(guān)于call和bind的區(qū)別

不多說(shuō),直接上代碼

回調(diào)函數(shù)中用call

更改函數(shù)的this指向,函數(shù)也會(huì)立即執(zhí)行,返回值是函數(shù)的執(zhí)行結(jié)果

var obj = {
    name: 'Dot'
}
function test(callback){
    console.log('callback:',callback)
    callback();
}
test(function(){
    console.log('name:',this)
}.call(obj))

//打印結(jié)果
//name: {name: "Dot"}
//callback: undefined
//Uncaught TypeError: callback is not a function
回調(diào)函數(shù)中用bind

更改函數(shù)的this指向,但是該函數(shù)不會(huì)立即執(zhí)行,返回值是更改了this指向的函數(shù)

var obj = {
    name: 'Dot'
}
function test(callback){
    console.log('callback:',callback)
    callback();
}
test(function(){
    console.log('name:',this)
}.bind(obj))

//  打印結(jié)果
//  callback: ? (){
//    console.log('name:',this)
//  }
//  name: {name: "Dot"}
函數(shù)執(zhí)行用call

更改函數(shù)this指向,同時(shí)立即執(zhí)行,沒(méi)有返回值

var obj = {
    name: 'Dot'
}
function printName() {
    console.log(this.name)
}
printName.call(obj)

//  打印結(jié)果
//  Dot
函數(shù)執(zhí)行用bind

更改函數(shù)this指向,但是函數(shù)不會(huì)立即執(zhí)行,而是返回一個(gè)更改this指向后的函數(shù)

var obj = {
    name: 'Dot'
}
function printName() {
    console.log(this.name)
}
var res = printName.bind(obj)
console.log(res)

//  打印結(jié)果
//  ? printName() {
//      console.log(this.name)
//  }

res()
//打印結(jié)果
// Dot
?著作權(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)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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