有项目要用到,没找到合适的 (也可能是没认真找)
于是自己写了个看起来还凑合的
// 创建新的构造函数
function ArrayWithEventEmitter() {
this.pushCallbacks = {
};
this.idPool = [];
}
// 设置构造函数的原型为 Array.prototype
ArrayWithEventEmitter.prototype = Object.create(Array.prototype);
// 修改构造函数的原型的 constructor 属性为 ArrayWithEventEmitter
ArrayWithEventEmitter.prototype.constructor = ArrayWithEventEmitter;
// 定义 push 方法
ArrayWithEventEmitter.prototype.push = function () {
// 调用注册的回调函数
Object.values(this.pushCallbacks).forEach(fn => fn());
// 调用对应的原生方法并返回结果(新数组长度)
return Array.prototype.push.apply(this, arguments);
}
ArrayWithEventEmitter.prototype.on = function (callback) {
let id;
if