2

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

持久数据:

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.
4

1 回答 1

1

没有必要做第二次FunctionTemplate。您在导出 ( ctor) 上设置的那个是在 JS 中调用时使用的那个new Event(),而第二个 ( localTemplate) 被保存到Event::tpl并且是从中进行HasInstance()调用的那个。它们是不同FunctionTemplate的 s,所以HasInstance()调用返回false

而不是这个:

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

试试这个:

...
tpl.Reset(ctor);
...
于 2018-11-06T21:43:49.903 回答