Câu hỏi phỏng vấn Javascript
Câu hỏi

What is the preferred syntax for defining enums in JavaScript?

Câu trả lời

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:

javascript Copy
var SizeEnum = {
  SMALL: 1,
  MEDIUM: 2,
  LARGE: 3
};

You can then use the enum like this:

javascript Copy
var mySize = SizeEnum.SMALL;

If you want the enum values to hold more properties, you can add them to an extra object like so:

javascript Copy
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:

javascript Copy
const DaysOfWeek = Object.freeze({
  SUNDAY: 0,
  MONDAY: 1,
  TUESDAY: 2,
  WEDNESD...
middle

middle

Gợi ý câu hỏi phỏng vấn

expert

Is JavaScript a pass-by-reference or pass-by-value language?

junior

What is a Polyfill?

junior

How to check if an object is an array or not? Provide some code

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào