bind可以干什么
使用了bind會創建一個新函數(綁定函數),當這個新函數被調用時,它的 this 值是傳遞給 bind() 的第一個參數, 它的參數是 bind() 的其他參數和新函數的參數。
語法:
fun.bind(thisArg[, arg1[, arg2[, ...]]])
- thisArg 當綁定函數被調用時,該參數會作為原函數運行時的 this 指向。當使用 new 操作符調用綁定函數時,該參數無效。
- arg1, arg2, … (可選)當綁定函數被調用時,這些參數加上綁定函數本身的參數會按照順序作為原函數運行時的參數。
使用介紹
//js提供的bind方法可以在函數運行之前就綁定其作用域,修改如下
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方法在低版本瀏覽器不兼容,這里我們可以手動實現一下
拆分思路
1.bind會返回一個新函數,所以
return function(){
}
2.目標是當這個新函數被調用時,它的 this 值是傳遞給 bind() 的第一個參數, 它的參數是 bind() 的其他參數以及新函數傳來的參數。
實現代碼
Function.prototype.testBind = function(that){
const arr = Array.prototype.slice.apply(arguments,[1]);
const _this = this;
return function(){
//目的:讓this指向obj,參數第一個就是{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參數傳遞 '+ a.value2)
console.log('調用參數傳遞 ' + b)
}
var obj = {
value:'ok'
}
var fun_new = test.testBind(obj,{value2:'also ok'})
fun_new ('hello bind');
每天都努力一點點
謝謝你看完