Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You could create the values as instances of the "class":</p> <pre><code>function TestEnum(value) { this._value = value; } TestEnum.prototype.valueOf = function() { return this._value; } TestEnum.prototype.toString = function() { return 'TestEnum_' + this._value; } TestEnum.VALUE_0 = new TestEnum(0); TestEnum.VALUE_1 = new TestEnum(1); </code></pre> <p>The following would work then:</p> <pre><code>TestEnum.VALUE_0 instanceof TestEnum </code></pre> <p>But it also means you'd have to explicitly access the numerical value of one value with <code>.valueOf</code>. In some cases JS will do this automatically for you (like in <code>5 + TestEnum.VALUE_1</code>). Overriding <code>toString</code> so that you can use a value as property might also be necessary.</p> <p>It really depends on your use case whether this is a viable solution.</p> <hr> <p>Alternatively, if just want to test whether a value is part of the enum, you can have an additional property which holds all possible values:</p> <pre><code>TestEnum.values = {0: true, 1: true, ...}; </code></pre> <p>And then test it with</p> <pre><code>value in TestEnum.values // or more reliable (fails for inherited `Object` properties) TestEnum.values.hasOwnProperty(value); </code></pre> <p>You could even automate this:</p> <pre><code>function collectValues(obj) { var values = {}; // or Object.create(null) if available for (var prop in obj) { if (obj.hasOwnProperty(prop)) { values[obj[prop]] = true; } } return values; } TestEnum.values = collectValues(TestEnum); </code></pre> <p>This will only reliably work for primitive values though and won't distinguish between the string <code>"1"</code> and the number <code>1</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload