手写call apply bind

故心故心故心故心小故冲啊

文章目录


call

 //1.手写步骤
    // 将函数设为对象的属性
    // 执行该函数
    // 删除该函数
    //细节 --参数问题 
    //this == null  =>指向的是window

    Function.prototype.myCall = function (context) {
        //细节 --参数问题  //获取参数
        //slice() 用于创建一个包含原有数组中一个或多个元素的新数组,不会影响原始数组 
        var args = [...arguments].slice(1);
        //1.将函数设为对象的属性  this值的是调用的那个函数
        context = context || window; 当context为null时候this指向的是window
        context.fn = this;
        //2.执行该函数  //执行函数的时候吧参数带上
        var result = context.fn(...args);
        //3.删除该函数
        delete context.fn;
        //4.返回这个结果
        return result;
    }

apply

跟call差不多 只是apply的第二次参数是数组 所以可以通过arguments[1]拿到这个参数

//手写myApply
    Function.prototype.myApply = function (context) {
    
        let result = null;
        //null的是指指向window
        context = context || window;
        //1.将该函数添加属性
        context.fn = this;
        //2.执行该函数,并带上参数
        // 调用方法
        if (arguments[1]) {
            result = context.fn(...arguments[1]);
        } else {
            result = context.fn();
        }
        //3删除该函数这个属性
        delete context.fn();
        //返回结果
        return result;
    }

bind

 //bind有是三个特点
    //1.返回一个函数
    //2.可以传入参数
    //3.bind 返回的函数作为构造函数的时候,bind 时指定的 this 值会失效,但传入的参数依然生效  =>new的时候this的指向变为obj了
    Function.prototype.myBind = function (context) {
        // 获取arguments[1]后面的参数
        let args = [...arguments].slice(1);
        let self = this;

        //1.返回一个函数
        return function Fn() {
            return self.apply(
                // 当作为构造函数时,this 指向实例,此时结果为 true,将绑定函数的 this 指向该实例,可以让实例获得来自绑定函数的值
                // 以上面的是 demo 为例,如果改成 `this instanceof Fn ? null : context`,实例只是一个空对象,将 null 改成 this ,实例会具有 habit 属性
                // 当作为普通函数时,this 指向 window,此时结果为 false,将绑定函数的 this 指向 context
                this instanceof Fn ? this : context,
                //2.可以传入参数
                args.concat(...arguments)
            )
            //3.bind 返回的函数作为构造函数的时候,bind 时指定的 this 值会失效,但传入的参数依然生效  =>new的时候this的指向变为obj了   
        }
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值