I’m trying to proxy the [[set]] method on JavaScript arrays. Is it possible to proxy all arrays, and not just a specific one? My handler would check the object being set in the array and if it hasOwnProperty('xyz')
then console.log
it.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy says that
I would do that with something like
set(target, prop, val) { // to intercept property writing
if (val.hasOwnProperty('xyz') {
console.log(prop);
};
target[prop] = val;
return true;
}
However, Proxy
seems to only work on single objects. Given that there is no prototype [[set]], how can I proxy this operation for every array?
Ideally, it would work something like this:
Array = new Proxy(Array, {
set(target, prop, val) { // to intercept property writing
if (val.hasOwnProperty('xyz') {
console.log(prop);
};
target[prop] = val;
return true;
}
});
let obj = {xyz: 1}
let list = [];
list[0] = obj; // would log 1
I tried the above code snippet, but it does not redefine the method for every array. One possible method could be to proxy Array.prototype.constructor to return an array with the [[set]] pre-proxied to have the check for the value.
Thanks!