javascript – 如何在ES Next中扩展静态属性?
作者:互联网
有时(尽管很少)你需要扩展,而不是覆盖父静态属性,例如下面的(非常蹩脚)示例:
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
如何在不破坏父属性的情况下扩展子类中的静态属性?
解决方法:
你可以这样做:
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.coreStats和Ninja.coreStats
标签:javascript,ecmascript-next 来源: https://codeday.me/bug/20190608/1200506.html