2

我正在包装一个 C++ 对象,node::ObjectWrap并且我定义了一些方法,例如:

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]
}

但我得到的是:

{}

关于如何使这些可见(又名可枚举)的任何想法?

4

1 回答 1

2

What you have is essentially

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);

The thing is that what is printed out does not include values in the prototype chain. So inst doesn't actually have any properties to print, hence {}. Only inst.__proto__ has properties. The properties are enumerable, so you could do Object.keys(inst.__proto__); to see them, but they aren't own properties of inst.

于 2014-07-18T17:01:00.120 回答