我正在使用 node::ObjectWrap
包装 C++ 对象,并且定义了一些方法,如下所示:
auto tpl = NanNew<v8::FunctionTemplate>(New);
tpl->SetClassName(NanNew("className"));
tpl->InstanceTemplate()->SetInternalFieldCount(4);
NanSetPrototypeTemplate(tpl, NanNew("method1") , NanNew<v8::FunctionTemplate>(Method1) , v8::ReadOnly);
NanSetPrototypeTemplate(tpl, NanNew("method2") , NanNew<v8::FunctionTemplate>(Method2), v8::ReadOnly);
NanSetPrototypeTemplate(tpl, NanNew("method3") , NanNew<v8::FunctionTemplate>(Method3) , v8::ReadOnly);
NanSetPrototypeTemplate(tpl, NanNew("method4") , NanNew<v8::FunctionTemplate>(Method4), v8::ReadOnly);
一切都按预期工作,我可以通过以下方式在 JS 中创建对象的实例:
var classInstance = new className();
所有方法都工作正常,但是当我尝试记录该函数时:
console.log(classInstance);
我期待看到类似的内容:
{
method1 : [Native Function],
method2 : [Native Function],
method3 : [Native Function],
method4 : [Native Function]
}
但是我得到的是:
{}
关于如何使这些可见(又名可枚举)有什么想法吗?
最佳答案
你所拥有的本质上是
var tpl = function(){};
tpl.prototype.method1 = function(){};
tpl.prototype.method2 = function(){};
tpl.prototype.method3 = function(){};
tpl.prototype.method4 = function(){};
var inst = new tpl();
console.log(tpl);
问题是打印出来的内容不包含原型(prototype)链中的值。所以inst
实际上没有任何要打印的属性,因此 {}
。仅inst.__proto__
有属性。这些属性是可枚举的,所以你可以这样做 Object.keys(inst.__proto__);
看到他们,但他们不是 own
inst
的属性.
关于c++ - 使 v8 对象属性和方法对 JS 可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24829459/