call

Function.prototype.myCall = function (thisArg, ...argArray) {
  const _thisArg = thisArg ? Object(thisArg) : {};

  const fn = Symbol('fn');
  _thisArg[fn] = this;

  const res = _thisArg[fn](...argArray);
  delete _thisArg[fn];
  return res;
};

apply

Function.prototype.myApply = function (thisArg, argArray) {
  const _thisArg = thisArg ? Object(thisArg) : {};

  const fn = Symbol('fn');
  _thisArg[fn] = this;

  const res = _thisArg[fn](...argArray);
  delete _thisArg[fn];
  return res;
};

bind

Function.prototype.myBind = function (thisArg = window, ...argArray) {
  const _thisArg = thisArg ? Object(thisArg) : {};

  const that = this;

  return function proxyFn(...args) {
    const fn = Symbol('fn');
    _thisArg[fn] = that;

    const res = _thisArg[fn](...args, ...argArray);

    delete _thisArg[fn];
    return res;
  };
};

test

const obj = {
  name: 'coderxie'
}

function foo(age, height) {
  console.log(this.name);
  console.log(age);
  console.log(height);
}



foo.myCall(obj, 18, 1.88)
foo.myApply(obj, [18, 1.88])
const foo2 = foo.myBind(obj, 18)
foo2(1.88)
最后修改:2022 年 08 月 11 日 10 : 54 AM
如果觉得我的文章对你有用,请随意赞赏