Js手写函数之bind、call、apply其实很简单

一、考察内容

  • this指向:this指向是谁调用指向谁,这句符合大部分场景。但是最准确的是this指向最近的调用者。如fun.test.myFun()指向的是text。
  • arguments:argument 对象包含了函数调用的参数数组
  • bind、call、apply的区别:
    • bind与call和apply的区别是bind返回一个函数,调用时不会立即执行。
    • call接收参数是分开的,apply接受是以数组的形式

二、手写bind

以代码注释形式讲解

/* 手写bind函数*/

Function.prototype.myBind =function(ctx,...arg){

    ctx = ctx||window     //若指向的对象不存在,则指向window

    ctx.fn = this		 //当前this是调用myBind方法的函数,也就是改变作用域的函数

    return function(){
        let args = [...arg,...arguments]   //合并返回函数中传入的参数
        ctx.fn(...args)
        delete ctx.fn     				   //删除作用域中本不存在的fn
    }
}
let a = 111
let b = 222

function test(){
    console.log(this.a,this.b,...arguments)
}

let mb = test.myBind({
    a:4,
    b:2
},1)


mb(111)

三、手写call

/* 手写call函数*/
Function.prototype.myCall =function(ctx,...arg){

    ctx = ctx||window

    ctx.fn = this

    ctx.fn(...arg)

    delete ctx.fn

}


function test2(){
    console.log(this.a,this.b,...arguments)
}

let call = test2.myCall({
    a:4,
    b:2
},1)

四、手写apply

/* 手写apply函数*/
Function.prototype.myApply =function(ctx,arg){

    ctx = ctx||window

    ctx.fn = this

    ctx.fn(...arg)

    delete ctx.fn

}


function test3(){
    console.log(this.a,this.b,...arguments)
}

let apply = test3.myApply({
    a:4,
    b:2
},[1,2,3])

总结:手写这三个函数其实很简单,主要是弄懂这三个函数的应用以及this的指向问题。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

名字还没想好☜

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

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

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

打赏作者

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

抵扣说明:

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

余额充值