Javascript 如何在 ES6 类中定义静态属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48012663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:59:38  来源:igfitidea点击:

how to define a static property in the ES6 classes

javascriptecmascript-6statices6-class

提问by Amir Azarbashi

I want to have a static property in an ES6 class. This property value is initially an empty array.

我想在 ES6 类中有一个静态属性。此属性值最初是一个空数组。

    class Game{

        constructor(){
           // this.cards = [];
        }

        static cards = [];
    }
    
    Game.cards.push(1);

    console.log(Game.cards);

How can I do it?

我该怎么做?

回答by zagoa

class Game{
   constructor(){}
}
Game.cards = [];

Game.cards.push(1);
console.log(Game.cards);

You can define a static variable like that.

您可以像这样定义一个静态变量。

回答by margaretkru

One way of doing it could be like this:

这样做的一种方法可能是这样的:

let _cards = [];
class Game{
    static get cards() { return _cards; }
}

Then you can do:

然后你可以这样做:

Game.cards.push(1);
console.log(Game.cards);

You can find some useful points in this discussionabout including static properties in es6.

你可以在这个关于在 es6 中包含静态属性的讨论中找到一些有用的点。