[英]How to interupt Array.push with Proxy?
我想在每次push
数组时添加一个副作用。 例如,我想添加console.log
:
var arr = [];
arr.push(1); // => I want it to work normally, and in addition, it logs 1 to the console
如何做到这一点? 我正在寻找使用Proxy
的解决方案,并且我尝试了handler.get()和handler.apply()但仍然无法弄清楚。
要直接回答您最初的问题...您需要从get
陷阱返回一个闭包。 但是,要实际捕获此问题,您需要使用proxy.push()
而不是array.push()
。 例如:
const arr = []; const arrProxy = new Proxy(arr, { get(target, prop) { if (prop === 'push') { return (...args) => { console.log(...args); return target[prop](...args); }; } return target[prop]; } }); arrProxy.push('test'); arrProxy.push('test1', 'test2');
这是我满意的最终答案,顺便说一下,它不使用Proxy
。
{ var arr = []; // add push arr.push = function (...items) { console.log(...items); Array.prototype.push.apply(this, items); }; arr.push('test'); arr.push('test1'); // clean up the push delete arr.push; }
类似的东西?
Object.defineProperty(Array.prototype, 'myPush', { value: function (...val) { console.log(...val) return this.push(...val) } }) let aa = [] aa.myPush( 5,123) console.log('aa = ', aa )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.