I need to emulate enum type in Javascript and approach seems pretty straight forward:
var MyEnum = {Left = 1; Right = 2; Top = 4; Bottom = 8}
Now, in C# I could combine those values like this:
MyEnum left_right = MyEnum.Left | MyEnum.Right
and then I can test if enum has certain value:
if (left_right & MyEnum.Left == MyEnum.Left) {...}
Can I do something like that in Javascript?
Enum Flags Attribute The idea of Enum Flags is to take an enumeration variable and allow it hold multiple values. It should be used whenever the enum represents a collection of flags, rather than representing a single value. Such enumeration collections are usually manipulated using bitwise operators.
Enums or Enumerated types are special data types that set variables as a set of predefined constants. In other languages enumerated data types are provided to use in this application. Javascript does not have enum types directly in it, but we can implement similar types like enums through javascript.
You just have to use the bitwise operators:
var myEnum = { left: 1, right: 2, top: 4, bottom: 8 } var myConfig = myEnum.left | myEnum.right; if (myConfig & myEnum.right) { // right flag is set }
More info:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With