重构call、apply、bind

本文详细介绍了JavaScript中call、apply、bind的逻辑重构,讲解了它们的使用区别。myCall和myApply实现了原生call和apply的功能,myBind则创建了一个新函数,保留了原函数的this上下文。这三种方法均用于改变函数执行时的this指向,对于理解和自定义函数行为至关重要。
摘要由CSDN通过智能技术生成

重构call、apply、bind

逻辑梳理

第一个参数为改变后this指向,第一个参数不存在则默认指向window

call后续参数不限制,apply只能拥有两个参数,且第二个参数必须为类数组

call与apply改变this指向后调用函数,bind改变this指向后返回一个新函数,不执行

call、apply、bind所有函数均可调用,因此,这三个方法均为函数原型对象上的属性

call

Function.prototype.myCall = function (invoke) {
            if(typeof this !== "function") throw new TypeError(`Uncaught TypeError: ${this}.call is not a function`); 
            invoke = invoke || window;
            invoke.fn = this;
            let args = [...arguments].slice(1);
            let result = invoke.fn(args);
            delete invoke.fn;
            return result;

        }

apply

Function.prototype.myApply = function(invoke){
            if(typeof this !== "function") throw new TypeError(`Uncaught TypeError: ${this}.apply is not a function`); 
            invoke = invoke || window;
            invoke.fn = this;
            let result = arguments[1] ? invoke.fn(...arguments[1]) : invoke.fn();
            delete invoke.fn;
            return result;
        }

bind

Function.prototype.myBind = function (invoke) {
            if (typeof this !== "function") throw new TypeError(`Uncaught TypeError: ${this}.bind is not a function`);
            let args = [...arguments].slice(1);
            let newThis = this;
            return function F(){
                return this instanceof F ? new newThis(...args, ...arguments) : newThis.apply(invoke, args.concat(...arguments))
            }
              
        }
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

菜鸟小胖砸

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

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

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

打赏作者

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

抵扣说明:

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

余额充值