It is known that you should not customize the built-in prototypes in JavaScript. But, what is the best way to add custom properties/methods to specific instances of theses classes? Things to consider are performance, clean code, easy to use, drawbacks/limitations etc...
I have in mind the following 4 ways to to this, and you are free to present your own. In the examples I have only 1 array and only 2 methods to add, but the question is about many objects with many additinal properties/methods.
1st way: Add methods directly to objects
let myArray1 = [1,2,3,2,1];
myArray1.unique = () => [...new Set(myArray1)];
myArray1.last = () => myArray1.at(-1);
2nd way, create a new (sub)class
class superArray extends Array{
constructor() {
super();
}
unique(){return [...new Set(this)]}
last(){return this.at(-1)}
}
let myArray2 = superArray.from([1,2,3,2,1]);
(The above example was updated, responding to @Bergi's comments)
3rd way, Object.assign
let superArrayMethods = {
unique: function(){return [...new Set(this)]},
last: function(){return this.at(-1)}
}
let myArray3 = [1,2,3,2,1];
myArray3 = Object.assign(myArray3, superArrayPrototype);
4th method, set prototype of an enhanced prototype of the Array prototype
let superArrayPrototype = {
unique: function(){return [...new Set(this)]},
last: function(){return this.at(-1)}
}
Object.setPrototypeOf(superArrayPrototype,Array.prototype);
let myArray4 = [1,2,3,2,1];
Object.setPrototypeOf(myArray4,superArrayPrototype);
In Chrome console, we see the four results:
The question!
What is the best way to add custom properties/methods to specific instances of built-in objects? And why?
Remember, the question is about creating many objects/arrays with (the same) many functions (that, of course, will be constructed/enhanced all together / in an organized fashion, not one by one as in these simplified examples!)
Does the same answer apply to other built-in objects, like HTML elements? What is the best way to add custom properties/methods to an HTML element? (maybe for another topic?)