手写apply

手写apply

方法一:ES6

Function.prototype.apply2 = function (context, arr) {
  context = context || globalThis;
  const _symbol = Symbol();
  context[_symbol] = this;
  let result = context[_symbol](...arr);
  delete context[_symbol];
  return result;
}

方法二:ES5

Function.prototype.apply3 = function (context, arr) {
  context = context || globalThis;
  context.fn = this;
  let result;
  if (!arr) {
    retult = context.fn();
  } else {
    let args = [];
    for (let i = 0, len = arr.length; i < len; i++) {
      args.push('arr[' + i + ']');
    }
    result = eval('context.fn(' + args + ')');
  }
  delete context.fn;
  return result;
}

参考文献

[1]如何模拟实现call、apply函数