Dave Dave - 2 months ago 10
C++ Question

Storing a JavaScript constructor for later use

I'm writing a node.js (0.12) library consisting of 50% Pure JavaScript classes and 50% Pure C++ classes. Certain functions in the C++ classes need to return instances of the JavaScript classes. I figure I need to store the constructors of the JavaScript classes in

Persistent<Function>
s. Assuming I can get the constructors as arguments how can I store them for later
NewInstance()
ing.

JS

function MyType()
{
this.a = 0;
};

native.store (MyType)


C++

void Wrapper::store (const FunctionCallbackInfo<Value>& args)
{
// Need to store args[0] as MyTypeConstructor for later
}

void Wrapper::use (const FunctionCallbackInfo<Value>& args)
{
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope (isolate);

auto ctor = Local<Function>::New
(isolate, MyTypeConstructor);

ctor->NewInstance();
}

Answer

I think I found the answer. Just like in the example under MyObject::Init you can use the Reset function to bind a local function to a persistent function.

Persistent<Function> MyTypeConstructor;

void Wrapper::store (const FunctionCallbackInfo<Value>& args)
{
    Isolate* isolate = Isolate::GetCurrent();
    HandleScope scope (isolate);

    auto ctor = Local<Function>::Cast (args[0]);
    MyTypeConstructor.Reset (isolate, ctor);
}