手写call

75 阅读1分钟

精髓:call方法我就是,传进来啥,我就用啥调用一下,返回个结果

// 每个function上都有的方法,我挂在Function的prototype上面吧
Function.prototype.customerCall = function (context, ...args) {
	// 边际条件,判断一下context传没传
    context = context == null ? window : context;
    // 定义一个返回结果
    let result;
    // 为传进来的 context 挂载一个临时方法fn1,这个赋值this就是fn
    context['fn1'] = this; 
    // 调用一下,返回你个结果
    result = context['fn1'](...args);
    // 好了,只是个临时方法,你没用了,把你删掉,避免后面再使用 context 时留坑
    delete context['fn1'];
    // 返回结果
    return result;
}
// 测试一下好使不

var a = 2;
var b = 3;
var obj = { a: 3, b: 5 };
var fn = function () { return this.a + this.b; }
fn.customerCall(obj)
// 好使,收工