手写call,apply,bind

call,apply,bind都属于Function对象的原型方法。

call和apply方法都会根据指定的this对象值来调用函数。

1、call方法

Function.prototype._call = function(obj){
        let that = this;
        if(typeof that != "function")
        {
            console.log("not function");
            return;
        }
        let arr = Array.from(arguments).slice(1),
            res = null;

        obj = obj || window;
        obj.fn = this;//this指向调用call的
        //调用函数。
        res = obj.fn(...arr);
        delete obj.fn;
        return res;
    }

        let obj = {
            name: 'obj'
        }
        var name = 'window'
        function f(a,b) {
            console.log( a+b )
        }

    f._call(obj,1,2);

​

 2、apply方法

apply方法以数组的形式接收其他参数

 实现过程:

1) 判断第二个参数是不是数组

2)将方法挂载到obj属性上

3)调用该方法

4)删除新增的obj属性

Function.prototype._apply = function(obj)
    {
        let that = this;
        let res = null;
        let arr = arguments[1];
        if(typeof that != "function")
        {
            console.log("不是函数");
            return;
        }   
        obj = obj || window;
        obj.fn = this;
        if(arr.length != 0)
        {
            res = obj.fn(...arr);
        }else{
            res = obj.fn();
        }
        delete obj.fn;
        return res;
    }
    f._apply(obj,[1,2]);

3、bind方法

bind方法不会直接调用函数,返回值是一个新的函数实例。

  Function.prototype._bind = function(obj){
        let that = this;
        if(typeof this != "function")
        {
            console.log("not function");
            return;
        }
        return ()=>{
            let arr = [...arguments].splice(1);
            let res = null;
            obj = obj || window;
            obj.fn = this;
            res = obj.fn(...arr);
            delete obj.fn;
            return res;
        }
    }

    f._bind(obj,1,2)();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值