Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Question] Why are the return values ​​of the two functions different? #444

Open
sdg9670 opened this issue Mar 21, 2024 · 1 comment

Comments

@sdg9670
Copy link

sdg9670 commented Mar 21, 2024

Napi::Object MyObject::NewInstance(Napi::Env env, Napi::Value arg) {
Napi::EscapableHandleScope scope(env);
Napi::Object obj = env.GetInstanceData<Napi::FunctionReference>()->New({arg});
return scope.Escape(napi_value(obj)).ToObject();
}

Napi::Value MyObject::Multiply(const Napi::CallbackInfo& info) {
Napi::Number multiple;
if (info.Length() <= 0 || !info[0].IsNumber()) {
multiple = Napi::Number::New(info.Env(), 1);
} else {
multiple = info[0].As<Napi::Number>();
}
Napi::Object obj = info.Env().GetInstanceData<Napi::FunctionReference>()->New(
{Napi::Number::New(info.Env(), this->value_ * multiple.DoubleValue())});
return obj;
}

I'm Newby, who just got into NAPI.
In the above two codes, methods are create and return the object.
I wonder why only the return value in NewInstance uses escape scope.

@mhdawson
Copy link
Member

mhdawson commented Apr 4, 2024

The different is that in the first case the creation of the object was done in the context of a scope

Napi::EscapableHandleScope scope(env);

You can read more about scopes in -> https://github.com/nodejs/node-addon-api/blob/main/doc/handle_scope.md#handlescope

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants