【发布时间】: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