如何在没有面向对象的情况下关联数值和function

我的函数init返回一个v8::Handle<Object> ,这个Object包含几个Handle<Function>属性,比如bar

 var foo = require('foo').init({a:'a', b:'b'}); foo.bar('a'); 

在我的插件代码中:

 Handle<Object> Bar (Arguments &args) { // !! how to access mystruct* p for current call? } Handle<Object> Init(Arguments &args) { HandleScope scope; mystruct* p = InitMyStructWithArgs(args); Object ret; // !! how to bind mystruct* p to Bar? NODE_SET_METHOD(ret, 'bar', Bar); scope.Close(ret); } 

你会发现Bar,Obj,args都是独立的,它们之间没有相对的关系,所以我不能在mystruct*使用{a:'a', b:'b'} mystruct*

您需要通过SetPointerInInternalField将您的自定义c ++对象绑定到返回的对象。

然后你可以通过你的对象函数的GetPointerFromInternalField来访问你的c ++对象。

C ++

 #include <v8.h> #include <node.h> using namespace v8; using namespace node; namespace { struct Sample { int counter; }; Handle<Value> Add(const Arguments& args) { HandleScope scope; Sample *sample = static_cast<Sample*>(args.This()->GetPointerFromInternalField(0)); return scope.Close(Number::New(sample->counter)); } Handle<Value> Init(const Arguments& args) { HandleScope scope; Sample* sample = new Sample(); sample->counter = 5; Local<ObjectTemplate> objectTemplate = ObjectTemplate::New(); objectTemplate->SetInternalFieldCount(1); Local<Object> ret = objectTemplate->NewInstance(); ret->SetPointerInInternalField(0, sample); ret->Set(String::New("add"), FunctionTemplate::New(Add)->GetFunction()); return scope.Close(ret); } extern "C" void init(Handle<Object> target) { HandleScope scope; target->Set(String::New("init"), FunctionTemplate::New(Init)->GetFunction()); } } // anonymous namespace 

JavaScript的

 var foo = test.init(); console.log(foo.add()); // 5 

参考

http://izs.me/v8-docs/classv8_1_1ObjectTemplate.html