bind、call、apply实现

bind的用法
1、生成新的函数
2、若生成的新函数作为构造函数,那么根传入的对象没有任何关系
3、可以作为偏函数使用

bind的js实现

if (!Function.prototype.bind) {
    Function.prototype.bind = function(that) {
        if (typeof this === 'function') {
            throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable')
        }
    
        var args = Array.prototype.slice.call(arguments,1);
        var fToBind = this;
        var fNop = function(){};

        // 返回的Fbind作为new的构造函数时,生成的新对象作为this传入Fbind,新对象的__proto__就是fNop的实例
        var Fbind = function() {
            args = args.concat(Array.prototype.slice.call(arguments));
            return fToBind.apply(this instanceof Fbind ? this : that, args);
        }
        
        // 维持原型链
        if (this.prototype) {
            fNop.prototype = this.prototype;
        }
        Fbind.prototype = new fNop();
    
        return Fbind;
    }
}

call实现

Function.prototype.call = function(that) {
    if (typeof this !== 'function') {
        throw new TypeError('Function.prototype.call-----is not a function');
    }
    var args = [...arguments].slice(1);
    that.fn = this;
    
    var result = that.fn(...args);
    Reflect.deleteProperty(that, 'fn');
    return result;
}

apply实现

Function.proptotype.apply = function() {
    if (typeof this !== 'function') {
        throw new TypeError('Function.prototype.apply-----is not a function');
    }
    that.fn = this;
    
    var result = 
    arguments[1]
    ? that.fn(...arguments[1])
    : that.fn();

    Reflect.deleteProperty(that, 'fn');
    return result;
}

原文地址

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值