Chris
Chris

Reputation: 58142

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?

Upvotes: 4

Views: 198

Answers (1)

Dmitriy Nevzorov
Dmitriy Nevzorov

Reputation: 6078

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

Upvotes: 5

Related Questions