What is the preferred syntax for defining enums in JavaScript?
What is the preferred syntax for defining enums in JavaScript?
In JavaScript, enums are not natively supported as they are in some other programming languages like Java or C#. However, developers can simulate enums using objects. The preferred syntax for defining enums in JavaScript involves creating an object with properties that represent the enum values. Here's an example of how you might define an enum for different sizes:
var SizeEnum = {
SMALL: 1,
MEDIUM: 2,
LARGE: 3
};
You can then use the enum like this:
var mySize = SizeEnum.SMALL;
If you want the enum values to hold more properties, you can add them to an extra object like so:
var SizeEnum = {
SMALL: 1,
MEDIUM: 2,
LARGE: 3,
properties: {
1: {name: "small", value: 1, code: "S"},
2: {name: "medium", value: 2, code: "M"},
3: {name: "large", value: 3, code: "L"}
}
};
var mySize = SizeEnum.MEDIUM;
var myCode = SizeEnum.properties[mySize].code; // myCode == "M"
This format combines the use of primitives as the enum values, which is safe for serialization and deserialization, with the ability to use objects to hold additional properties[1].
Another approach to creating immutable enums in JavaScript is to use the Object.freeze()
method, which prevents any changes to the object after it's created:
const DaysOfWeek = Object.freeze({
SUNDAY: 0,
MONDAY: 1,
TUESDAY: 2,
WEDNESD...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào