Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proxy "Array.prototype.push"

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?

like image 281
bread Avatar asked Jun 26 '26 23:06

bread


1 Answers

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

like image 62
Konrad Linkowski Avatar answered Jun 29 '26 12:06

Konrad Linkowski