使用 Geddy 在 Node.js 中声明和使用枚举
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15301698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Declare and use an enum in Node.js with Geddy
提问by Sorin Adrian Carbunaru
For my model I want to have an enumeration as a datatype, but I don't know how to do that. I couldn't find anything helpful in the documentation from geddyjs.org or with google.
对于我的模型,我希望将枚举作为数据类型,但我不知道该怎么做。我在来自 geddyjs.org 或谷歌的文档中找不到任何有用的东西。
A model could be defined like this:
一个模型可以这样定义:
var fooModel= function () {
this.defineProperties({
fooField: {type: 'datatype'},
.............................
});
}
Where and how should I define the enumeration and how do I use it?
我应该在哪里以及如何定义枚举以及如何使用它?
回答by Nick Mitchinson
Remember that Node is just javascript, and javascript does not (to the best of my knowledge) have enums. You can however fake it, which is discussed here: Enums in JavaScript?
请记住,Node 只是 javascript,而 javascript(据我所知)没有枚举。但是,您可以伪造它,这在这里讨论:JavaScript 中的枚举?
回答by Shahar Shokrani
My preferred Enum package for node is https://www.npmjs.com/package/enum.
我首选的节点枚举包是https://www.npmjs.com/package/enum。
Here is a basic usage (copied from documentation):
这是一个基本用法(从文档中复制):
// use it as module
var Enum = require('enum');
// or extend node.js with this new type
require('enum').// define an enum with own values
var myEnum = new Enum({'A': 1, 'B': 2, 'C': 4});
And then you can use for example a simple switch case statement like:
然后您可以使用例如一个简单的 switch case 语句,例如:
let typeId = 2;
switch (typeId) {
case myEnum.A.value:
//Do something related to A.
break;
case myEnum.B.value:
//Do something related to B.
break;
case myEnum.C.value:
//Do something related to C.
break;
default:
//Throw error
break;
}
回答by Tolga E
There are modules out there that do this, one of which is https://npmjs.org/package/simple-enum(simple one I created)
有一些模块可以做到这一点,其中之一是https://npmjs.org/package/simple-enum(我创建的简单模块)

