Search code examples
javascriptecmascript-next

How do you extend static properties in ES Next?


Sometimes (albeit rarely) you need to extend, rather than overwrite parent static properties, such as (the very lame) example below:

class Person {
    static coreStats = {
        role: "slacker",
        weapon: null,
        speed: 4,
        vechicle: "roller blades",
    };
}

class Ninja extends Person {
    static coreStats = {
        role: "silent assassin",
        weapon: "katana",
        speed: 99,
    };
}

console.log(Ninja.coreStats); // But vechicle is no more

How does one extend the static properties in a child class without clobbering the parent properties?


Solution

  • you can do it like this:

    class Person {
        static coreStats = {
            role: "slacker",
            weapon: null,
            speed: 4,
            vechicle: "roller blades",
        };
    }
    
    class Ninja extends Person {
        static coreStats = Object.assign({}, Person.coreStats, {
            role: "silent assassin",
            weapon: "katana",
            speed: 99
        });
    }
    console.log(Ninja.coreStats);
    

    This will merge coreStats and override Person.coreStats with Ninja.coreStats in case of duplications