扩展Array.push方法

我正在尝试使用自定义推送方法扩展特定数组:

let instance = {
  'queue': []
};

instance.initQueue = () => {
  let _this = instance;

  _this['queue'].push = func => {
    if (typeof func === 'function') {
      // default
      Array.prototype.push.apply(this,arguments);

      // process
      _this.processQueue();
    }
  };

  _this.processQueue();
};

instance.processQueue = () => {
  let _this = instance;

  _this['queue'].forEach((func,idx,obj) => {
    if (typeof func === 'function') {
      func.call(func);
    }

    obj.splice(idx,1);
  });
};

instance.initQueue();
instance.queue.push(() => console.log(1))

当我尝试触发push方法(instance.queue.push(() => console.log(1));时,什么也没有发生。如果我将initQueue函数包装为超时,那么它就起作用了:

setTimeout(() => { instance.initQueue(); },100);

任何合理的解释为什么会发生这种情况?

linshi0 回答:扩展Array.push方法

在消除明显的语法错误之后,您的代码似乎可以正常工作:

let instance = {
  'queue': []
};

instance.initQueue = () => {
  let _this = instance;

  _this['queue'].push = (func,...rest) => {
    if (typeof func === 'function') {
      // default
      Array.prototype.push.apply(_this['queue'],[func,...rest]);

      // process
      _this.processQueue();
    }
  };

  _this.processQueue();
};

instance.processQueue = () => {
  let _this = instance;

  _this['queue'].forEach((func,idx,obj) => {
    if (typeof func === 'function') {
      func.call(func);
    }

    obj.splice(idx,1);
  });
};

instance.initQueue();
instance.queue.push(() => console.log(1))

将函数推入队列后立即被调用,原因是:

// process
_this.processQueue();

您可以将其删除以自己控制队列的处理。

本文链接:https://www.f2er.com/3167682.html

大家都在问