JS(11)、手写call、apply、bind

本文介绍了如何在JavaScript中自定义实现Function对象的call、apply和bind方法,用于改变函数的this指向以及绑定参数。myCall和myApply分别模拟了call和apply的功能,myBind则创建了一个新的函数,其this被固定为传入的参数,并可预设函数调用时的参数。
摘要由CSDN通过智能技术生成
  • 1、call()方法使用一个指定的this值和单独给出的一个或多个参数来调用一个函数(即、可以改变当前函数的this指向,还会让当前函数执行)
Function.prototype.myCall = function(context){
    //首先判断调用对象是否是函数
    if(typeof this !== 'function'){
        console.error("type error");
    }

    //获取参数(截取第一个参数后的所有参数)
    let args = [...arguments].slice(1)
    let result = null

    //判断context是否传入,没有传入将其设置为window
    context = (context === null || context === undefined)? window:context

    //给context添加fn属性,并把调用函数设置为fn的属性值
    //这时候执行context.fn,便是在context上调用这个函数了
    context.fn = this

    //调用函数
    context.fn(...args)

    //将属性删除
    delete context.fn
    return result
}

  • 2、apply(),该方法与call()基本相同
  • 实现如下:
Function.prototype.myApply = function(context){
    if(typeof this !== 'function'){
        console.error("type error");
    }

    context = (context === null || context === undefined)? window:context
    context.fn = this

    let result = arguments[1]? context.fn(...arguments[1]):context.fn()

    delete context.fn
    return result
}
  • 3、bind()会返回一个新的函数,不会自动执行。这个函数的this值被指定为bind()的第一个参数,而其余参数将作为新函数的参数,供调用时使用
Function.prototype.myBind = function(context){
    if(typeof this !== 'function'){
        console.error("type error");
    }

    //获取参数
    let args = [...arguments].slice(1)
    let ts = this

    return function Fn(){
        return ts.apply(
            this instanceof Fn ? this : context,
            args.concat(...arguments)
        )
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值