JavaScript可擴展枚舉封裝

枚舉結構

一般咱們定義的枚舉值:javascript

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

使用var mySize = SizeEnum.SMALL;java

若是須要包含其餘屬性,咱們能夠添加額外的對象數組

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"}
  }
};

使用:this

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

封裝

下面咱們進行封裝:prototype

/**
 * 枚舉類
 *
 * @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;
  }
}

使用方法:code

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/...](對象

相關文章
相關標籤/搜索