day033: 能不能实现一个 call/apply 函数?

2021-03-11 14:39:51 浏览数 (1)

引自冴羽大佬的代码,可以说比较完整了。

代码语言:javascript复制
Function.prototype.call = function (context) {
    let context = context || window;
    let fn = Symbol('fn');
    context.fn = this;

    let args = [];
    for(let i = 1, len = arguments.length; i < len; i  ) {
        args.push('arguments['   i   ']');
    }

    let result = eval('context.fn('   args  ')');

    delete context.fn
    return result;
}

不过我认为换成 ES6 的语法会更精炼一些:

代码语言:javascript复制
Function.prototype.call = function (context, ...args) {
  let context = context || window;
  let fn = new Symbol('fn');
  context.fn = this;

  let result = eval('context.fn(...args)');

  delete context.fn
  return result;
}

类似的,有apply的对应实现:

代码语言:javascript复制
Function.prototype.apply = function (context, args) {
  let context = context || window;
  context.fn = this;
  let result = eval('context.fn(...args)');

  delete context.fn
  return result;
}

0 人点赞