Node.js本机插件中的枚举类型

时间:2013-03-26 04:55:17

标签: c++ node.js enums v8

是否可以在Node.js插件的C ++代码中创建一些enum,然后将此类型公开给js代码?我发现js中存在本机枚举类型,但是没有关于它们在v8引擎中实现的信息。

3 个答案:

答案 0 :(得分:4)

请注意,在Kevin给出的示例中,您需要在使用之前创建Local<Object>的实例,因此请务必致电Object::New()

Local<Object> obj = Object::New();
const char* k = "HEADERS_RECEIVED";
int v = 1;
obj->Set(v8::String::NewSymbol(k), v8::Int32::New(v), ReadOnly); // Use PropertyAttribute ReadOnly so that value won't be changed by javascript.

答案 1 :(得分:3)

javascript中没有特定的枚举类型,而是使用常量int,例如在web中,UNSENT,OPENED, HEADERS_RECEIVED,LOADING,DONE的属性XMLHttpRequest在C ++中定义为枚举类型。要在v8中为javascript导出这些属性,请使用:

Local<Object> obj;
const char* k = "HEADERS_RECEIVED";
int v = 1;
obj->Set(v8::String::NewSymbol(k), v8::Int32::New(v), ReadOnly); // Use PropertyAttribute ReadOnly so that value won't be changed by javascript.

答案 2 :(得分:1)

根据最新的v8 API ref

,现在已经改变了
Isolate* isolate = args.GetIsolate();
Local<Context> context = isolate->GetCurrentContext();
Local<Object> obj;
obj->DefineOwnProperty(
                       context,
                       String::NewFromUtf8(isolate,"enum"),
                       Number::New(isolate,1), v8::ReadOnly
                       );