手動實現(xiàn)JS bind()

bind可以干什么

使用了bind會創(chuàng)建一個新函數(shù)(綁定函數(shù)),當這個新函數(shù)被調(diào)用時,它的 this 值是傳遞給 bind() 的第一個參數(shù), 它的參數(shù)是 bind() 的其他參數(shù)和新函數(shù)的參數(shù)。
語法:

fun.bind(thisArg[, arg1[, arg2[, ...]]])

  • thisArg 當綁定函數(shù)被調(diào)用時,該參數(shù)會作為原函數(shù)運行時的 this 指向。當使用 new 操作符調(diào)用綁定函數(shù)時,該參數(shù)無效。
  • arg1, arg2, … (可選)當綁定函數(shù)被調(diào)用時,這些參數(shù)加上綁定函數(shù)本身的參數(shù)會按照順序作為原函數(shù)運行時的參數(shù)。

使用介紹

//js提供的bind方法可以在函數(shù)運行之前就綁定其作用域,修改如下

const id = 'window';
function test () {
    console.log(this.id)
}

const fn = test.bind(window);
const obj = {
    id: 'obj',
    hehe:fn
};

fn();// window
obj.hehe(); // window


但是bind方法在低版本瀏覽器不兼容,這里我們可以手動實現(xiàn)一下

拆分思路

1.bind會返回一個新函數(shù),所以

return function(){

}

2.目標是當這個新函數(shù)被調(diào)用時,它的 this 值是傳遞給 bind() 的第一個參數(shù), 它的參數(shù)是 bind() 的其他參數(shù)以及新函數(shù)傳來的參數(shù)。

實現(xiàn)代碼

Function.prototype.testBind = function(that){
  
    const arr = Array.prototype.slice.apply(arguments,[1]);
  
    const _this = this;
    
  
  return function(){
    //目的:讓this指向obj,參數(shù)第一個就是{value2:'also ok'},第二個是“hello bind”
    _this.apply(that,arr.concat(Array.prototype.slice.call(arguments)));
  }
    
}

測試

var test = function(a,b){
    console.log('作用域綁定 '+ this.value)
    console.log('testBind參數(shù)傳遞 '+ a.value2)
    console.log('調(diào)用參數(shù)傳遞 ' + b)
}
    
var obj = {
    value:'ok'
}
var fun_new = test.testBind(obj,{value2:'also ok'})

fun_new ('hello bind');

每天都努力一點點
謝謝你看完


最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容