js中的bind()的使用与手写bind()

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]); 第二个参数是一个数组

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值