# 手写bindcall函数

# call函数

  • 改变this指向
  • 返回执行结果
Function.prototype.myCall = function(thisArg, ...Args){
    const thisObj = thisArg || window; // this指向获取不到时,指向window
    const tempVar = Symbol("temp");
    thisObj[tempVar] = this; // 将函数存入thisObj的临时变量。this是被改变this执行的那个函数
    let result = thisObj[tempVar](...Args);
    delete thisObj[tempVar]; // 删除临时变量
    return result;
}

# bind函数

  • 改变this指向
  • 返回一个函数
  • new
Function.prototype.myBind = function(thisArg,...Args){
    const thisFn = this; // 保存当前调用的函数
    let funcHasBind = function(...Args2){
        const isNew = this instanceof funcHasBind;
        const thisObj = isNew ? this : thisArg;
        return thisFn.myCall(thisObj, ...Args, ...Args2);
    }
    funcHasBind.prototype = Object.create(thisFn.prototype);
    return funcHasBind;
}
作者:王龙楷; 标签:原创; 提交时间: 1/14/2021, 4:22:34 PM