繁体   English   中英

扩展 Array.push 方法

[英]Extend Array.push method

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

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

当我试图触发推送方法( instance.queue.push(() => console.log(1));时,什么也没有发生。如果我用超时包装initQueue function - 它的工作:

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM