/********************************************************************* * NAN - Native Abstractions for Node.js * * Copyright (c) 2018 NAN contributors * * MIT License ********************************************************************/ #include using namespace Nan; // NOLINT(build/namespaces) class MyObject : public node::ObjectWrap { public: static NAN_MODULE_INIT(Init); private: MyObject(); ~MyObject(); static NAN_METHOD(New); static Persistent constructor; }; Persistent MyObject::constructor; MyObject::MyObject() { } MyObject::~MyObject() { } void Foo(FunctionCallbackInfo const&) {} NAN_MODULE_INIT(MyObject::Init) { // Prepare constructor template v8::Local tpl = Nan::New(New); tpl->SetClassName(Nan::New("MyObject").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); // Prototype SetPrototypeTemplate( tpl , "prototypeProp" , Nan::New("a prototype property").ToLocalChecked()); // Instance SetInstanceTemplate( tpl , "instanceProp" , Nan::New("an instance property").ToLocalChecked()); // PropertyAttributes SetInstanceTemplate( tpl , Nan::New("none").ToLocalChecked() , Nan::New("none").ToLocalChecked() , v8::None); SetInstanceTemplate( tpl , Nan::New("readOnly").ToLocalChecked() , Nan::New("readOnly").ToLocalChecked() , v8::ReadOnly); SetInstanceTemplate( tpl , Nan::New("dontEnum").ToLocalChecked() , Nan::New("dontEnum").ToLocalChecked() , v8::DontEnum); SetInstanceTemplate( tpl , Nan::New("dontDelete").ToLocalChecked() , Nan::New("dontDelete").ToLocalChecked() , v8::DontDelete); v8::Local function = Nan::GetFunction(tpl).ToLocalChecked(); constructor.Reset(function); Set(target , Nan::New("MyObject").ToLocalChecked() , function); //=== SetMethod ============================================================== v8::Local obj = Nan::New(); SetMethod(obj, "foo", Foo); // https://github.com/nodejs/nan/issues/564 v8::Local func = Nan::New(Foo); SetMethod(func, "foo", Foo); v8::Local t = Nan::New(Foo); SetMethod(t, "foo", Foo); } NAN_METHOD(MyObject::New) { if (info.IsConstructCall()) { MyObject* obj = new MyObject(); obj->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } else { v8::Local cons = Nan::New(constructor); info.GetReturnValue().Set(Nan::NewInstance(cons).ToLocalChecked()); } } NODE_MODULE(settemplate, MyObject::Init)