bind()
:主要用于更改this的指向问题,obj.myFun.bind(obj, 'str1', ... , 'strN' )
;
基本使用如下:
function fn1(a, b, c) {
console.log('this', this);
console.log(a, b, c);
return 'this is fn1'
}
const fn2 = fn1.bind({ x: 100 }, 10, 20, 30); // bind 返回一个值再次调用
const res = fn2(); // this {x: 100} 10 20 30
console.log(res); // this is fn1
手写自定义bind1
的使用
// 模拟 bind
Function.prototype.bind1 = function() {
// 将参数拆解为数组
const args = Array.prototype.slice.call(arguments);
// 获取 this 的第一项对象, 剩下的传入的数组参数
const t = args.shift();
const self = this;
return function() {
return self.apply(t, args);
}
}
// 自定义bind1的使用
const fn3 = fn1.bind1({ x: 200 }, 20, 20, 30); // bind 返回一个值再次调用
const bind1res = fn3(); // this {x: 200} 20 20 30
console.log(bind1res); // this is fn1
call()、apply()、bind()的用法区别
call(): obj.myFun.call(obj, 'str1', ... , 'strN' )
;
bind(): obj.myFun.bind(obj, 'str1', ... , 'strN' )
; 返回一个新的函数
apply(): obj.myFun.bind(obj, [Array])
; 第二个参数是一个数组