In JavaScript you can extend the functionality of an object with prototype.
Person.prototype.fullName = function () {
return this.first + this.last;
};
I run into scenarios a lot where I need to process something on an array of specific objects. These are cases where it would be nice for the functionality to be linked to that object type, as opposed to just passing as an array parameter. I am aware that it is unadvised to extend the JavaScript Array.
Is there an equivalent standard to extend the functionality of an array of objects? Here is a pseudo-example of what I mean:
Person(Array).prototype.groupByAges = function () {
// logic here that would group by ages
// { '0-15': [person, person], '16-18': [person, person], etc. }
return list;
};
// could be used like this
const list = persons.groupByAges();
What I have tried:
- writing functions like
getAgeGroupsByPerson(arr)which end up cluttering code JQuery.grep()and JavaScriptarr.map()which help but does not link the functionality to that specific object type.
Note: I realize that there may be better ways to logically solve the specific age grouping problem that I have described. It is just an example to demonstrate my point. Thank you.
Array.prototype.groupByAges = function(){ }wherethisis the reference to the current array.MyArrayLikeClass.prototype = new Array()and thenMyArrayLikeClass.prototype.someMethod = function() {}