手写 apply 函数实现,手摸手分享实现

  • Post author:
  • Post category:其他


apply 方法是实现思路和上一篇的 call 实现思路是一样的,只不过 apply 方法的第二个参数是数组,因此不需要用到剩余参数,在第二个参数不传的情况下,dyapply内部逻辑或赋值默认空数组[]就可以了

Function.prototype.dyapply = function (thisArgs, argArray) {
  // 1.获取到要执行的函数
  var fn = this;
  // 2.处理绑定的 thisArgs
  thisArgs = (thisArgs !== null && thisArgs !== undefined) ? Object(thisArgs) : window;
  // 3.执行函数
  thisArgs.fn = fn;

  argArray = argArray || [];

  var result = thisArgs.fn(...argArray);
  return result;
  delete thisArgs.fn;
};



版权声明:本文为frontendchen原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。