Javascript Enum To Corresponding String Value

前端 未结 8 1988
攒了一身酷
攒了一身酷 2021-01-07 17:06

So I have this in the javascript for my page:

var TEST_ERROR  = {
        \'SUCCESS\'   :   0,
        \'FAIL\'      :   -1,
        \'ID_ERROR\'  :   -2
            


        
8条回答
  •  再見小時候
    2021-01-07 17:44

    You could always have the values be objects of a particular type.

    var TEST_ERROR = (function() {
      function ErrorValue(value, friendly) {
        this.value = value;
        this.friendly = friendly;
      }
      ErrorValue.prototype = {
        toString: function() { return this.friendly; },
        valueOf: function() { return this.value; }
      };
      return {
        'SUCCESS': new ErrorValue(0, 'Success'),
        'FAIL': new ErrorValue(1, 'Fail'),
        'ID_ERROR': new ErrorValue(2, 'ID error')
      };
    })();
    

    Now when you get a value of that type:

    var err = testFunction(whatever);
    

    you can get the string value with

    alert(err.toString());
    

    In fact you shouldn't even have to call .toString() explicitly, most of the time.

提交回复
热议问题