【问题标题】:Checking instanceof in node.js addons using Nan使用 Nan 检查 node.js 插件中的 instanceof
【发布时间】:2018-05-30 15:19:08
【问题描述】:

我试图在打开并开始使用它之前验证传递给节点插件的对象是否属于正确的类型。这是我通过查看网络上的各种资源拼凑而成的解决方案。

持久数据:

Nan::Persistent<v8::Function> Event::constructor;
Nan::Persistent<v8::FunctionTemplate> Event::tpl;

初始化函数:

void Event::Init(v8::Local<v8::Object> exports) {
    Nan::HandleScope scope;

    // Prepare constructor template
    v8::Local<v8::FunctionTemplate> ctor = Nan::New<v8::FunctionTemplate>(Event::New);
    ctor->InstanceTemplate()->SetInternalFieldCount(1);
    ctor->SetClassName(Nan::New("Event").ToLocalChecked());

    // create a template for checking instances
    Local<FunctionTemplate> localTemplate = Nan::New<FunctionTemplate>(Event::New);
    localTemplate->SetClassName(Nan::New("Event").ToLocalChecked());
    tpl.Reset(localTemplate);

    // Statics
    Nan::SetMethod(ctor, "x", Event::X);

    // Prototype
    Nan::SetPrototypeMethod(ctor, "addInfo", Event::addInfo);
    Nan::SetPrototypeMethod(ctor, "toString", Event::toString);

    constructor.Reset(ctor->GetFunction());
    Nan::Set(exports, Nan::New("Event").ToLocalChecked(), ctor->GetFunction());
}

以及我尝试使用它的地方:

    if (Nan::New(tpl)->HasInstance(info[0])) {
        message = "it is an Event instance";
    }

问题是 HasInstance() 永远不会返回 true。

JavaScript 代码基本上是

let e = new Event()
fn(e)     // where fn performs the HasInstance() test.

【问题讨论】:

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


    【解决方案1】:

    没有必要再发第二个FunctionTemplate。您在导出中设置的一个 (ctor) 是您在 JS 中调用 new Event() 时使用的那个,而第二个 (localTemplate) 保存到 Event::tpl 并且是其中的一个HasInstance() 调用成功。它们是不同的FunctionTemplates,所以HasInstance() 调用返回false

    而不是这个:

    ...
    Local<FunctionTemplate> localTemplate = Nan::New<FunctionTemplate>(Event::New);
    localTemplate->SetClassName(Nan::New("Event").ToLocalChecked());
    tpl.Reset(localTemplate);
    ...
    

    试试这个:

    ...
    tpl.Reset(ctor);
    ...
    

    【讨论】:

    • 我已经按照你的建议解决了这个问题,但忘记了我问过这个问题。这里没有太多关注 Nan/NAPI 的内容。但是您的答案很准确并且很有帮助!谢谢。
    猜你喜欢
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-23
    • 1970-01-01
    • 2017-08-30
    相关资源
    最近更新 更多