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

Napi::Obj Get or Set by copy #971

Closed
aminya opened this issue Apr 14, 2021 · 2 comments
Closed

Napi::Obj Get or Set by copy #971

aminya opened this issue Apr 14, 2021 · 2 comments

Comments

@aminya
Copy link

aminya commented Apr 14, 2021

I have faced a situation in which I need to make a new object in JavaScript from C++.

But, when I Get a property of some object and Set it to another object, I get these circular references in the JavaScript code while I wanted a copy (a surprising behavior which I figured out by a lot of debugging!).

Apparently, the copy constructor (Napi::Object(ref)) has no effect on the JS side.

The JavaScript solution is to use something like copy = Object.assign({}, obj_ref). I want to know if there is a C++ solution too or I need to call the same thing from C++.

Napi::Object copy(const Napi::Object &obj, const Napi::Env &env) {
    auto obj_copy = Napi::Object::New(env);
    env.Global().Get("Object").As<Napi::Object>().Get("assign").As<Napi::Function>().Call({ obj_copy, obj });
    return obj_copy;
}
@legendecas
Copy link
Member

The copy constructor simply means copy the reference (you can call it a pointer to the JavaScript value or anything else) but not copy the JavaScript values. This matches across many other JavaScript engines' native API design.

As far as I can tell, using existing node-api and node-addon-api the solution you proposed is the one you can use across various Node.js versions.

@mhdawson
Copy link
Member

I'm going to close this as there has been no further discussion since the initial answer to the question. Please let us know if you feel that was not the right thing to do.

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

3 participants