原生js实现手写call、apply、bind

48 篇文章 0 订阅
43 篇文章 11 订阅

实现call()方法

call都做了哪些操作?

  1. 将函数设为对象的属性;
  2. 指定this到函数,并传入给定参数执行函数;
  3. 执行之后删除这个函数;
  4. 如果不传入参数,默认指向window;
Function.prototype.mycall = (context,...args) => {
    // 判断this是否函数,否返回typeerror
    if (typeof this !== 'function') {
        throw new TypeError('不是函数');
    }

    context = context || window;
    context.fn = this;

    const res = context.fn(...args);

    delete context.fn;
    return res; 
}

实现apply()

apply跟call类似

Function.prototype.myapply = (context,args) => {
    if (typeof this !== 'function') {
        throw new TypeError('不是函数');
    }

    context = context || window;
    context.fn = this;
    args = args && args || [];

    const res = context.fn(...args);

    delete context.fn;
    return res;
}

实现bind()

bind要做什么?

  1. 返回一个函数,绑定this,传递预制参数;
  2. bind返回的参数可以作为构造函数使用。
Function.prototype.mybind = (context,...args) => {
    if (typeof this !== 'function') {
        throw new TypeError('不是函数');
    }

    let fn = this;
    
    const bind = (...args2) => {
        // fn.apply 来保持上下文和执行bind时一致;
        // this instanceof bind 是在构建函数new 操作时判断是否为 bind的实例;
        // bind之后的函数再执行还会传参,[...args,...args2] 用来整合参数

        return fn.apply(this instanceof bind ? this : context, [...args,...args2]);
    }

    bind.prototype = Object.create(this.prototype);

    return bind;
}

bind解析:

bind函数返回的是一个可执行函数,所以最后 return 了一个函数,此刻返回的函数,在执行的时候,this应该保持和传入对象一致,所以需要使用 apply绑定;

bind需要做到可以接收传参,并将参数传给目标函数,而后再执行时传的参数,要接在之前参数的后边,所以使用[...argus, ...argus2]来进行参数整合;

再对 bind后的对象 执行 new 操作时,this应该指向当前对象,所以在 fn.apply 的第一个参数,做了这样的判断this instanceof bind ? this : context;

bind 执行后返回的函数 修改 prototype 时,不应该影响到 fn.prototype ,两者应该是独立的,所以使用 bind.prototype = Object.create(this.prototype) 隔离开。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

前端卡卡西呀

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

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

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

打赏作者

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

抵扣说明:

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

余额充值