首页 > 解决方案 > 扩展 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);

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

标签: javascriptarraysecmascript-6

解决方案


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

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();

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


推荐阅读