通过篡改数组原型方法实现监听。
代码片段:
let arr = [1, 2, 3];
// 篡改原 push 方法之前,先将原 push 方法保存起来
let _push = Array.prototype.push;
Array.prototype.push = (val)=>{
// 在这里面就可以写监听后出来的代码...
console.log('我监听了push方法添加数组元素',val);
// 在最后再调用保存下来的原生方法_push
// 并且因为push方法是实例方法,所以this指向调用者,最后再将 val 传给原生_push方法
_push.call(this,val);
}
以上就实现了对数组数据的监听。