在JavaScript中模擬Java的enum

來源:互聯網
上載者:User

標籤:

背景

最近開始做的一個項目使用facebook的ReactJS前端架構。發現經常使用react的keyMirror工具來定義一些枚舉常量:

var keyMirror = require(‘keyMirror‘);var AppMode = keyMirror({    LOG_IN: null,    SIGN_UP: null});module.exports = AppMode;

其他JS代碼對該枚舉的引用大概如下代碼:

var AppMode = require(‘../const/app_mode‘);if (curMode == AppMode.LOG_IN) {    ...} else {    ...}...var className = (curMode == AppMode.LOG_IN) ? ‘login-form‘ : ‘signup-form‘;...

這樣的代碼感覺還行,起碼比字串漫天飛舞的情況好很多。不過我發現諸如curMode == AppMode.LOG_IN類型的代碼太多了,寫起來不太舒服,而且總是要求我require(‘../const/app_mode‘),我希望能簡單地寫類似於curMode.isLogIn()的代碼。所以就搞了這個簡單的工具gen_enum:

用法

npm install gen_enum

var createEnum = require(‘gen_enum‘);var COLORS = createEnum("blue red");var myColor = COLORS.blue;console.log(myColor._id); // output blueconsole.log(myColor.isBlue()); //output trueconsole.log(myColor.isRed()); //output falseconsole.log(myColor.name()); //output blueconsole.log(myColor.toString()); //output blue

輸入: "key1 key2 ..."

注意,除空白以外關鍵字還可以用,, ; 以及:來分割

輸出:

{    key1: {        _id: ‘key1‘,        name: function() {            return ‘key1‘;        },        toString: function() {            return ‘key1‘;        },        isKey1: function() {            return true;        },        isKey2: function() {            return false;        }    },    key2: {        _id: ‘key2‘,        name: function() {            return ‘key2‘;        },        toString: function() {            return ‘key2‘;        },        isKey1: function() {            return false;        },        isKey2: function() {            return true;        }    }}
其他輸入形式

使用字串來指定枚舉關鍵字只是一種方式,gen_enum還支援其他兩種形式的輸入:

// 用字串數組來指定枚舉關鍵字var Color = genEnum("blue", "red");var myColor = Color.blue;// 用Object對象來指定枚舉關鍵字var WeekDay = genEnum({    Monday: null,    Tuesday: null})var myDay = WeekDay.Monday;
關於 CamelCase

gen_enum將大寫加底線的枚舉關鍵字的isXXX函數名轉換為CamelCase形式:

var AppMode = genEnum(‘SIGN_UP, LOG_IN, FORGOT_PASSWORD‘);var curMode = AppMode.LOG_IN;console.log(curMode.isLogIn()); // 輸出 trueconsole.log(curMode.isSignUp()); // 輸出 falseconsole.log(curMode.isForgotPassword()); // 輸出 false

項目地址:

  • https://github.com/greenlaw110/enumjs
  • https://www.npmjs.com/package/gen_enum

在JavaScript中模擬Java的enum

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.