简体   繁体   English

在 JavaScript 中实现枚举的最佳方法是什么?

[英]Which is the best way to implement enums in JavaScript?

I was thinking about a nice way to implement an enum-like structure in JavaScript.我正在考虑一种在 JavaScript 中实现类枚举结构的好方法。 I came up with a few solutions but which one is the best to use?我想出了一些解决方案,但哪一个最好用?

static getter class:静态吸气剂类:

class Enum {
    static get A() {
        return 0;
    }

    static get B() {
        return 1;
    }

    static get C() {
        return 2;
    }
}

This can be used like var a = Enum.A // a == 0 .这可以像var a = Enum.A // a == 0

Online I found a solution using an object an freezing it:我在网上找到了一个使用对象冻结它的解决方案:

const enum = {
    A: 0,
    B: 1,
    C: 2
}

Object.freeze(enum);

This can be used like var b = enum.B // b = 1 .这可以像var b = enum.B // b = 1

I am wondering if one of this methods is better in performance and in memory usage?我想知道其中一种方法在性能和内存使用方面是否更好?

You can use as below:您可以使用如下:

const Colors = Object.freeze({
    A: 0,
    B: 1,
    C: 2
});

I tested both methods and the class method of implementing an Enum is really the worst.我测试了这两种方法,实现 Enum 的类方法确实是最糟糕的。 So I will stick to freezing an Object.所以我会坚持冻结一个对象。

The only case where the class method performed better was when using the enum at many different Spots in the code (in different modules usw...)类方法表现更好的唯一情况是在代码中的许多不同位置使用枚举(在不同的模块中...)

But thanks to everyone answering.不过谢谢大家的回答。

You can use TypeScript:您可以使用打字稿:

enum MyEnum {
 A = 0,
 B = 1,
 C = 2
}

But if you need vanilla JS, here's code compiled by TS Compiler:但是如果你需要 vanilla JS,这里是 TS Compiler 编译的代码:

var MyEnum;
(function (MyEnum) {
    MyEnum[MyEnum["A"] = 0] = "A";
    MyEnum[MyEnum["B"] = 1] = "B";
    MyEnum[MyEnum["C"] = 2] = "C";
})(MyEnum || (MyEnum = {}));

Hope, this will help希望,这会有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM