【问题标题】:How do I create an ES6 class in V8 (for a Node.js native add-on)?如何在 V8 中创建 ES6 类(用于 Node.js 原生插件)?
【发布时间】:2018-08-11 08:14:03
【问题描述】:

我正在编写一个 Node.js 原生插件(带有 nan 辅助模块)。 我想创建并导出一个 ES6 类值,其 type"function".toString()"class ... { ... }"。即,我想知道原生等价物:

module.exports = class CLASS_NAME {};

.


我在 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)

但它只会改变函数的名称:

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

,它根本不创建 ES6 类。


我该怎么做?

【问题讨论】:

    标签: javascript node.js v8 node.js-addon node.js-nan


    【解决方案1】:

    我认为您需要通过调用其SetClassName(v8::String) 方法来命名函数模板。

    如果你的函数模板是一个构造函数,通过设置符号getToStringTag 来命名它的原型对象模板也是一个好主意:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-24
      • 2018-10-06
      • 1970-01-01
      相关资源
      最近更新 更多