Thanks to inheritance, we can define our own collection type based on arrays: create our own class that will be inherited from Array:
class Team extends Array { constructor(name, ...members) { super(...members); this.name = name; } }
Here we assume that the first parameter of the class constructor is the name of the command, and the second – a set of team players, the number of which is not fixed.
Thanks to inheritance from Array, we can treat objects of the Team class as data sets and apply to them all those operations that apply to arrays:
class Team extends Array { constructor(name, ...members) { super(...members); this.name = name; } } // create command object const barcelona = new Team("Barcelona", "Tom", "Sam", "Bob"); console.log(barcelona); // Team(3) ["Tom", "Sam", "Bob"] // enumeration of the set for (const person of barcelona) { console.log(person); } barcelona.push("Tim"); // add one element console.log(barcelona); // Team(4) ["Tom", "Sam", "Bob", "Tim"] barcelona.splice(1, 1); // remove the second element console.log(barcelona); // Team(3) ["Tom", "Bob", "Tim"]
Overriding standard methods
We can override inherited standard array methods.
class Team extends Array { constructor(name, ...members) { super(...members); this.name = name; } //override standard push method push(person) { if (person !== "admin") super.push(person); } } const snowbars = new Team("Dinamo", "Tom", "Sam", "Bob"); snowbars.push("admin"); // add one element - admin console.log(snowbars); // Team(3) ["Tom", "Sam", "Bob"] snowbars.push("Tim"); // add one element - Tim console.log(snowbars); // Team(4) ["Tom", "Sam", "Bob", "Tim"]