简体   繁体   English

如何在V8中创建ES6类(用于Node.js本机附加组件)?

[英]How do I create an ES6 class in V8 (for a Node.js native add-on)?

I'm writing a Node.js native add-on (with nan helper module). 我正在编写一个Node.js本机加载项(带有nan helper模块)。 I want to create and export an ES6 class value, whose type is "function" and .toString() is "class ... { ... }" . 我想创建和导出 ES6类值,其类型"function".toString()"class ... { ... }" Viz., I want to know the native equivalent of: 即,我想知道本机等效项:

module.exports = class CLASS_NAME {};

.


The only thing I could find on the V8 documentation for doing this, was .SetName() . 我在V8文档中唯一可以找到的是.SetName()

#include <nan.h>

#define LOCAL_STRING(c_string) (Nan::New(c_string).ToLocalChecked())
#define LOCAL_FUNCTION(c_function) \
    (Nan::New<v8::FunctionTemplate>(c_function)->GetFunction())

void method(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
    info.GetReturnValue().Set(LOCAL_STRING("world"));
}

void initialize_module(
    v8::Local<v8::Object> exports,
    v8::Local<v8::Object> module
)
{
    v8::Local<v8::Function> f = LOCAL_FUNCTION(method);
    f->SetName(LOCAL_STRING("FUNCTION_NAME")); // The only thing I could do
    module->Set(
        LOCAL_STRING("exports"),
        f
    ); // module.exports = f;
}

NODE_MODULE(blahblah, initialize_module)

But it only alters the name of a function: 但这只会更改函数的名称:

module.exports = function FUNCTION_NAME { ...... };

, which does not create an ES6 class at all. ,它根本不会创建ES6类。


How do I do this? 我该怎么做呢?

I think you need to name the function template by calling its SetClassName(v8::String) method. 我认为您需要通过调用其SetClassName(v8::String)方法来命名函数模板。

If your function template is a constructor, it is also a good idea to name its prototype object template by setting symbol getToStringTag like: 如果您的函数模板是构造函数,则通过设置符号getToStringTag来命名其原型对象模板也是一个好主意,例如:

prototype_template->Set(
    v8::Symbol::GetToStringTag(isolate),
    v8::String::New(isolate, "prototype_name"),
    static_cast<v8::PropertyAttribute>(...);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM