存储 JavaScript 构造函数供以后使用

Storing a JavaScript constructor for later use

我正在编写一个 node.js (0.12) 库,其中包含 50% 纯 JavaScript 类 和 50% 纯 C++ 类。 C++ 中的某些函数 类 需要 return JavaScript 类 的实例。我认为我需要将 JavaScript 类 的构造函数存储在 Persistent<Function> 中。假设我可以获得构造函数作为参数,我该如何存储它们以备后用 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();
}

我想我找到了答案。就像在 MyObject::Init 下的 example 中一样,您可以使用 Reset 函数将本地函数绑定到持久函数。

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);
}