Skip to content

jsbind 函数 ​

本节目标:理解“jsbind 函数”的核心思路,并能把它用于实际开发或面试表达。

Function.prototype.myBind = function (context, ...args) {
  // 判断调用对象是否为函数
  if (typeof this !== 'function') {
    throw new TypeError('Error');
  }
  const fn = this;
  return function Fn(...innerArgs) {
    return fn.apply(this instanceof Fn ? this : context, [
      ...args,
      ...innerArgs,
    ]);
  };
};
在函数Fn的内部,如果this instanceof Fn,表明是使用new 进行调用;

本站总访问 — 次