I was looking around online and I saw someone do something similar, Array.prototype.push was proxied and every push was handled, I want to do something like this:
new Proxy(Array.prototype.push, handler);
const array = [];
array.push("e"); // logs "e" to the console somehow from the handler
How can this be achieved?
This will work:
const handler = {
apply(target, thisArg, argumentsList) {
console.log(`called push with argument:', ${argumentsList}`);
return Reflect.apply(target, thisArg, argumentsList)
}
};
Array.prototype.push = new Proxy(Array.prototype.push, handler);
const a = []
a.push(1)
More info:
MDN article about Proxy
handler.apply
But it can break things so be careful
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With