没有OO如何相关的价值和功能

时间:2011-12-18 18:47:02

标签: c++ design-patterns node.js v8

我的功能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'} Bar p>

1 个答案:

答案 0 :(得分:2)

实施例

您需要通过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