4

有时(尽管很少)您需要扩展而不是覆盖父静态属性,例如下面的(非常蹩脚的)示例:

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

如何在不破坏父属性的情况下扩展子类中的静态属性?

4

1 回答 1

5

你可以这样做:

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);

如果出现重复,这将合并coreStats并覆盖Person.coreStatsNinja.coreStats

于 2016-04-29T09:55:59.997 回答