函数里call、apply、bind的实现,手写call、apply、bind

回顾以前学习内容,并记录如下

手写call、apply、bind

Function.prototype.myCall = function (context) {
    // 如果不是函数调用则返回,即 fn.myCall(),此处this为fn
    if (typeof this !== 'function') return;
    // 判断是否传入了要改变的this指向的参数,没有则指向window
    // 即fn.myCall(obj) 将fn的上下文改为obj
    const ctx = context ?? window;
    // 此处this即为fn函数,将它设置为obj的属性
    // 以obj.fn 形式调用即fn的上下文为obj
    ctx.fn = this;
    // 获取参数
    const arr = [...arguments].slice(1);
    // 传入参数获取结果
    const result = ctx.fn(...arr);
    // 调用或删除它
    delete ctx.fn;
    // 返回调用结果
    return result;
}

//同理 不同的是参数的形式,Apply的参数为数组
Function.prototype.myApply = function (context) {
    if (typeof this !== 'function') return;
    let ctx = context ?? window;
    let arr = arguments[1];
    ctx.fn = this;
    let result = ctx.fn(arr);
    delete ctx.fn;
    return result;
}

//同理
Function.prototype.myBind = function (context) {
    if (typeof this !== 'function') return;
    const ctx = context ?? window;
    ctx.fn = this;
    const arr = [...arguments].slice(1);
    return function () {
        ctx.fn(...arr)
    }
}

Array.prototype.myforEach = function (callback) {
    if (!Array.isArray(this)) throw 'this not a array';
    let list = this;
    for (let i = 0; i < list.length; i++) {
        callback(list[i]);
    }
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
call、applybind都是用来改变函数中的this指向的方法。其中,call和apply可以直接调用函数并传递参数,而bind则返回一个新的函数,需要手动调用。 具体实现方案如下: - call的实现: 1. 给想要绑定的对象设置一个属性,并将该属性指向需要调用的函数。 2. 使用该对象调用函数,并传递参数。 3. 结束调用后,删除该属性。 - apply实现: 1. 给想要绑定的对象设置一个属性,并将该属性指向需要调用的函数。 2. 使用该对象调用函数,并传递参数数组。 3. 结束调用后,删除该属性。 - bind实现: 1. 创建一个新的函数,并将原函数作为其中的属性保存起来。 2. 当新函数被调用时,将之前绑定的对象作为this,并传递参数。 3. 返回新函数供后续调用。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [如何实现call、applybind](https://blog.csdn.net/XIAO_A_fighting/article/details/116701887)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [原生JS实现 call apply bind](https://download.csdn.net/download/weixin_38628990/14046564)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值