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?
You just have to use the bitwise operators:
More info:
Yes, bitwise arithmetic works in Javascript. You have to be careful with it because Javascript only has the
Number
data type, which is implemented as a floating-point type. But, values are converted to signed 32-bit values for bitwise operations. So as long as you don't try to use more than 31 bits, you'll be fine.I've tried to create an example that demonstrates a common use case where one may want to use bit mask enums to control logging verbosity. It demonstrates the us of JavaScript bit-wise operations: See it on JSFiddle
In javascript you should be able to combine them as:
Then testing would be exactly as it is in your example of