Расширить метод Array.push - PullRequest
       3

Расширить метод Array.push

2 голосов
/ 04 ноября 2019

Я пытаюсь расширить определенный массив с помощью специального метода 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);

Есть ли разумное объяснение, почему это происходит?

1 Ответ

0 голосов
/ 04 ноября 2019

После удаления очевидных синтаксических ошибок ваш код, кажется, работает:

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

Вы можете удалить его, чтобы самостоятельно управлять обработкой очереди.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...