call、apply&bind

封装函数 f,使 f 的 this 指向指定的对象

function bindThis(f, oTarget) {
    return function(){
       return f.call(oTarget, ...arguments)
    }
}

function bindThis(f, oTarget) {
    return function(){
       return f.apply(oTarget, arguments)
    }
}

function bindThis(f, oTarget) {
    return f.bind(oTarget)
}

解释call、apply和bind,举个例子

    <script>
        const Bob = {
            name: 'Bob',
            score: 90,
            up: function (num){
                this.score = num
            }
        }
        const Allen = {
            name: 'Allen',
            score: 60,
        }
        console.log(Bob) /* {name: "Bob", score: 90, up: ƒ} */
        Bob.up(100)
        console.log(Bob);/* {name: "Bob", score: 100, up: ƒ} */
        console.log(Allen);/* {name: "Allen", score: 60} */

        Bob.up.call(Allen, 70)
        console.log(Allen);/* {name: "Allen", score: 70} */

        Bob.up.apply(Allen, [80])
        console.log(Allen);/* {name: "Allen", score: 80} */
        
        const upup = Bob.up.bind(Allen)
        upup(90)
        console.log(Allen);/* {name: "Allen", score: 90} */
    </script>

         现在有Bob和Allen两个同学,Bob成绩好score,他有一个刷题秘籍up,只要想要多少分通过那个up就可以实现。但是Allen没有那个up刷题秘籍,他想提分,就只能找Bob借刷题秘籍,Bob也愿意借给他,然后Allen就可以使用Bob的刷题秘籍up了。

        Bob.up.call(Allen,70),Bob把up秘籍借给Allen,Allen将分数提到了70分。

        Bob.up.apply(Allen,[80]),同样借出去了,但是通过apply借出去分数得用【】包起来()这是规定。

        const upup = Bob.up.bind(Allen);upup(90). 通过bind的方式借出去,Allen珍惜这次机会,可以灵活地在想刷分的时候刷分即可。

运行结果: 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值