####22重写call&&bind

67 阅读1分钟

call重写

Function.prototype.call = function call(ctx, ...params) {
    //=> 判断为 null/undefined
    if(ctx == null) {
      ctx =window;
    }
    
    //=> 其它原始值类型 Object(ctx)
    if(/!/^(object|function)$/.test(typeof ctx)) {
       ctx = Object(ctx);
    }

    //this -> fn ctx -> obj params -> [10, 20]
    //思路:就是给ctx加上一个唯一的属性 等物 this,调用的时候 ctx.xxx(...params)
    let self = this,
        key = Symbol('KEY'),
        result;
    ctx[key] = self;
    result = ctx[key](...params);
    //=> 移除新增的属性
    delete ctx[key];
    // Reflect.deleteProperty(ctx, key); //=> es6的方式删除
    return result;
}

function fn(x, y) {
    console.log(x)
    return x + y
}
const obj = {
    name: 'obj'
}
fn.call(obj, 10, 20)

重写 bind

Function.prototype.bind = function(ctx, ...params) {
    let self = this;// this -> 方法
    return (...args) {
        params = params.concat(args);
        return self.call(ctx, params);
    }
}