Array inheritance in JavaScript. Code example open

Array inheritance in JavaScript. Code example

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators

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"]
0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation