I know how to add a custom property to an object.
Lets say I have a foo method,
const foo = () => { console.log('custom method'); }
I can add the foo
method to the Array prototype and call it using array variables by
Array.prototype.foo = foo;
And then if I create an array called,
bar = [1, 2, 3];
and run
bar.foo()
It will execute my custom foo method. But I don't know how to run the foo
method every time an array is created and every time an array is updated.
I want to run a custom method and store some data during array creation/updating in JavaScript. How do I do that?
Lets say I have a custom method,
const customMethod = () => {
...doing some stuff
}
I want this custom method to run every time an array is created and store some data in that array. Like I want to find the maximum of the array and store it inside the array with key maximum
as we are storing length
now. So that after creating/updating the array I don't have to calculate the maximum. I can just call myArray.maximum
and will get that maximum value.
This approach does something similar. But it requires to add event listener and a new push method so that it can fire an event everytime something pushed into the array using that custom push method. But in that case my custom function will not be updated if I use regular Array.prototype.push
method or create a new array using spread operator like this, newArr = [...oldArray, value]
.
Update: After searching and with the help of the links in comment I found out that it is not possible to modify the Array object without extending it or creating a custom array type from scratch(which is not acceptable).
I have tried to extend the existing Array type and create MyCustomArray. But it doesn't work as an array at all.
class MyCustomArray extends Array {
constructor(...args) {
super(...args);
console.log('custom array');
}
}
Any idea how can I extend the Array to create my CustomArray type and add a listener to it, so that every time I create/update a CustomArray it calculates the max and set it as an array max attribute (With minimum code change)?
So my CustomArray will have all the methods and instance variables like a normal array. But it will do one extra thing, every time I update/create a CustomArray it will calculate the max in that array and set it as property.