[英]Extend Array.push method
I'm trying to extend a specific array with custom 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))
While I'm trying to trigger the push method ( instance.queue.push(() => console.log(1));
, nothing happen. If I'll wrap the initQueue
function with a timeout - it's work:当我试图触发推送方法( instance.queue.push(() => console.log(1));
时,什么也没有发生。如果我用超时包装initQueue
function - 它的工作:
setTimeout(() => { instance.initQueue(); }, 100);
Any reasonable explanation of why this is happening?为什么会发生这种情况的任何合理解释?
After removing the obvious syntax errors, your code seems to be working:删除明显的语法错误后,您的代码似乎可以正常工作:
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))
The functions are being called as soon as they're pushed in the queue, that's because of:这些函数一被推入队列就会被调用,这是因为:
// process
_this.processQueue();
You can remove it to control the processing of the queue yourself.您可以将其删除以自己控制队列的处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.