JavaScript idiom for limiting a string to a number of discrete values

In C# I might use an enumeration.

In JavaScript, how can I limit a value to a set of discrete values idiomatically?


We sometimes define a variable in a JS class 'Enumerations' along these lines:

var Sex = {
    Male: 1,
    Female: 2
};

And then reference it just like a C# enumeration.


There is no enumeration type in JavaScript. You could, however, wrap an object with a getter and setter method around it like

var value = (function() {
   var val;
   return {
      'setVal': function( v ) {
                   if ( v in [ listOfEnums ] ) {
                       val = v;
                   } else {
                       throw 'value is not in enumeration';
                   }
                },
      'getVal': function() { return val; }
   };
 })();

Basically, you can't.

Strong typing doesn't exist in JavaScript, so it's not possible to confine your input parameters to a specific type or set of values.

链接地址: http://www.djcxy.com/p/91770.html

上一篇: JavaScript,定义不可修改的枚举

下一篇: 用于将字符串限制为多个离散值的JavaScript惯用法