call、apply、bind的源码模拟

1、call

Function.prototype.customCall = function(ctx){
    ctx.fn = this;
    let args = [...arguments].slice(1);
    let result = ctx.fn(...args);
    delete ctx.fn;
    return result
}

2、apply

Function.prototype.customApply = function(ctx){
    ctx.fn = this;
    let result = arguments[1] ? ctx.fn(arguments[1]) : ctx.fn();
    delete ctx.fn;
    return result
}

3、bind

Function.prototype.customBind = function(ctx){
    let that = this;
    let args = [...arguments].slice(1);
    return function(){
        that.apply(ctx, args);
    }
}

 

  

posted @ 2020-06-27 20:15  泛舟青烟  阅读(224)  评论(0编辑  收藏  举报