javascript - 扩展 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);
为什么会发生这种情况的任何合理解释?
解决方案
删除明显的语法错误后,您的代码似乎可以正常工作:
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();
您可以将其删除以自己控制队列的处理。
推荐阅读
- javascript - 按键事件期间输入文本上未显示字符-knockoutjs
- sql - 将 2 个 SQL 查询合并为一个查询
- elasticsearch - 运行 logstash 时出现 IllegalStateException
- flutter - PageView 更改当前位置时状态不更新
- javascript - JavaScript - 文本框 - 根据光标/突出显示的位置从字符串/文本框中删除字符
- airflow - 如何从 DAG 中删除任务
- c++ - 在找到 x 项之前的系列总和时出现意外错误
- python - 可以将字符串转换为整数,每个字符串中都有一个单词python
- python-3.x - 如何打印通过 python 中的参数传递的函数的名称?
- charts - Google Charts - 列和表格图表显示在同一页面中