js--call、apply、bind手写

67 阅读1分钟
exports.call = function (context, ...args) {
  // this 为调用方法 例:f.call this = f
  context.fn = this;
  const result = context.fn(...args);
  delete context.fn;
  return result;
};
exports.apply = function (context, args) {
    return this.call(context,...args)
};

或者重写
exports.apply = function (context, args) { // 只需要变动一行 ...args => args
  // this 为调用方法 例:f.call this = f
  context.fn = this;
  const result = context.fn(...args);
  delete context.fn;
  return result;
};
exports.bind = function (context, ...args) {
  // this 为调用方法 例:f.call this = f
  const f = this;
  return function F() {
    return f.apply(context, [...args, ...arguments]);
  };
};

  • 1、apply和call的区别:
    • apply第二个参数是数组或者类数组,call的参数是打散传入的