gpt4 book ai didi

javascript - 使用 Nan 检查 node.js 插件中的 instanceof

转载 作者:行者123 更新时间:2023-11-29 20:58:41 26 4
gpt4 key购买 nike

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

持久数据:

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.

最佳答案

无需制作第二个FunctionTemplate。您在导出 (ctor) 上设置的那个是您在 JS 中调用 new Event() 时使用的那个,而第二个 ( localTemplate) 被保存到 Event::tpl 并且是 HasInstance() 调用的来源。它们是不同的 FunctionTemplate,因此 HasInstance() 调用返回 false

取而代之的是:

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

试试这个:

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

关于javascript - 使用 Nan 检查 node.js 插件中的 instanceof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47848851/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com