简体   繁体   中英

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. 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 .

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 .

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. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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