实现 call 、apply、bind

55 阅读1分钟
/**
 * @desc: 实现 call apply bind 方法
 * @param {*} thisArg 
 * @param {array} args
 * @example:
 * @author:
 */
Function.prototype.myCall = function (thisArg, ...args) {
  const key = Symbol("key");
  thisArg[key] = this;
  let res = thisArg[key](...args);
  delete thisArg[key];
  return res;
};

Function.prototype.myApply = function (thisArg, args) {
  const key = Symbol("key");
  thisArg[key] = this;
  let res = thisArg[key](...args);
  delete thisArg[key];
  return res;
};

Function.prototype.myBind = function (thisArg, ...args) {
  return (...resArgs) => {
    return this.call(thisArg, ...args, ...resArgs);
  };
};