JS中 bind()的用法,call(),apply(),bind()异同点及使用,如何手写一个bind()

✨什么是bind()

bind()的MDN地址

bind() 方法创建一个新函数,当调用该新函数时,它会调用原始函数并将其 this 关键字设置为给定的值,同时,还可以传入一系列指定的参数,这些参数会插入到调用新函数时传入的参数的前面。

🍧 call(),apply(),bind()的异同

🎐 相同点

三者都是动态的修改函数内部的this指向

🎶 不同点

  • 传参方式不同,call()和bind()是按照顺序传参,apply()是通过数组/伪数组传参。
  • 执行机制不同,call()和apply()是立即执行函数,bind()不会立即执行函数,而是会返回一个修改过this的新函数。

🍿 call()

函数名.call(修改后的this,形参1,形参2…)

    person = {
      name: 'zhangsan'
    }
    function fn (a, b,) {
      console.log(this) //{name: 'zhangsan'}
      console.log(a, b) //1 2 
      console.log(a + b) //3
    }
    //call 立即执行函数 没有返回值
    let res = fn.call(person, 1, 2)
    console.log(res); //undefined

在这里插入图片描述

🎄apply()

函数名.apply(修改后的this,数组/伪数组)

    person = {
      name: 'zhangsan'
    }
    function fn (a, b) {
      console.log(this) //{name: 'zhangsan'}
      console.log(a, b) //1 2 
      console.log(a + b) //3
    }
    //apply 立即执行函数 没有返回值
    let res = fn.apply(person, [1, 2])
    console.log(res) //undefined

在这里插入图片描述

🎡 bind()

函数名.bind(修改后的this,形参1,形参2…)

  person = {
      name: 'zhangsan'
    }
    function fn (a, b, c, d) {
      console.log(this) //{name: 'zhangsan'}
      console.log(a, b, c, d) //1 2 3 4
      console.log(a + b + c + d) //10
    }
    //bind 不会立即执行函数,而是返回一个修改this的新函数
    let newFn = fn.bind(person, 1, 2)
    newFn(3, 4)

在这里插入图片描述

✨ 手写bind() :myBind()

可参照上一篇文章 手写call()

🎡代码

Function.prototype.myBind = function (thisArg, ...args) {
       
      return (...reArgs) => {
        // this:原函数(原函数.myBind)
        return this.call(thisArg, ...args, ...reArgs)
      }
    }
    
    // ------------- 测试代码 -------------
    const person = {
      name: 'zhangsan'
    }

    function func(numA, numB, numC, numD) {
      console.log(this)
      console.log(numA, numB, numC, numD)
      return numA + numB + numC + numD
    }

    const bindFunc = func.myBind(person, 1, 2)

    const res = bindFunc(3, 4)
    console.log('返回值:', res)

🎉 测试

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

、信仰_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值