2 #include <node_object_wrap.h>
8 using v8::FunctionCallbackInfo;
9 using v8::FunctionTemplate;
18 class MyObject : public node::ObjectWrap {
20 static void Init(v8::Local<v8::Object> exports);
23 explicit MyObject(double value = 0);
26 static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
27 static void PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args);
28 static v8::Persistent<v8::Function> constructor;
32 Persistent<Function> MyObject::constructor;
34 MyObject::MyObject(double value) : value_(value) {
37 MyObject::~MyObject() {
40 void MyObject::Init(Local<Object> exports) {
41 Isolate* isolate = exports->GetIsolate();
43 // Prepare constructor template
44 Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
45 tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject"));
46 tpl->InstanceTemplate()->SetInternalFieldCount(1);
49 NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne);
51 constructor.Reset(isolate, tpl->GetFunction());
52 exports->Set(String::NewFromUtf8(isolate, "MyObject"),
56 void MyObject::New(const FunctionCallbackInfo<Value>& args) {
57 Isolate* isolate = args.GetIsolate();
59 if (args.IsConstructCall()) {
60 // Invoked as constructor: `new MyObject(...)`
61 double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
62 MyObject* obj = new MyObject(value);
63 obj->Wrap(args.This());
64 args.GetReturnValue().Set(args.This());
66 // Invoked as plain function `MyObject(...)`, turn into construct call.
68 Local<Value> argv[argc] = { args[0] };
69 Local<Context> context = isolate->GetCurrentContext();
70 Local<Function> cons = Local<Function>::New(isolate, constructor);
71 Local<Object> result =
72 cons->NewInstance(context, argc, argv).ToLocalChecked();
73 args.GetReturnValue().Set(result);
77 void MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) {
78 Isolate* isolate = args.GetIsolate();
80 MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.Holder());
83 args.GetReturnValue().Set(Number::New(isolate, obj->value_));
86 void InitAll(Local<Object> exports) {
87 MyObject::Init(exports);
90 NODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)