JavaScript可扩展枚举封装

枚举结构

通常我们定义的枚举值:

var SizeEnum = {
  SMALL: 1,
  MEDIUM: 2,
  LARGE: 3,
};

使用var mySize = SizeEnum.SMALL;

如果需要包含其他属性,我们可以添加额外的对象

var SizeEnum = {
  SMALL: 1,
  MEDIUM: 2,
  LARGE: 3,
  properties: {
    1: {name: "small", value: 1, code: "S"},
    2: {name: "medium", value: 2, code: "M"},
    3: {name: "large", value: 3, code: "L"}
  }
};

使用:

var mySize = SizeEnum.MEDIUM;
var myCode = SizeEnum.properties[mySize].code; // myCode == "M"

封装

下面我们进行封装:

/**
 * 枚举类
 *
 * @author harris.xc
 * @param props  [{key: number|string, value: number|string, ...other}]
 * 栗子:
 *  const StepEnum = new Enum([
 *    { key: 'STEP1', name: '步骤1', value: 1 },
 *    { key: 'SETP2', name: '步骤2', value: 2 },
 *  ]);
 *
 * @class Enum
 *
 * @method get(value) 通过value获取当前列的值
 *                    return { key: 'SETP2', name: '步骤2', value: 2 }
 *
 * @returns {key1: number|string, key2: number|string}
 * {
 *   CREATE: 1,
 *   APPROVED: 2,
 * }
 */
export default class Enum {
  /**
   * 初始化
   * @param {Array} props []
   */
  constructor(props = []) {
    this.__props = {};
    if (props.length) {
      props.forEach((element) => {
        if (element.key && element.value) {
          this[element.key] = element.value;
          this.__props[element.value] = element;
        } else {
          console.error('Enum缺少必要的key或value');
        }
      });
    }
  }

  /**
   * 根据value获取对象值
   * @param {string|number} value 状态值
   */
  get(value) {
    return this.__props[value];
  }
 
  /**
   * 获取枚举数组
   */
  getArray() {
    const arr = [];
    for (const key in this.__props) {
      if (Object.prototype.hasOwnProperty.call(this.__props, key)) {
        arr.push(this.__props[key]);
      }
    }
    return arr;
  }
}

使用方法:

let SizeEnum = new Enum([
    { key: 'STEP1', name: '步骤1', value: 1 },
    { key: 'SETP2', name: '步骤2', value: 2 }
]);

SizeEnum.STEP1; // 1
SizeEnum.get(SizeEnum.STEP1); // { key: 'STEP1', name: '步骤1', value: 1 }

[https://stijndewitt.com/2014/...](

相关推荐