1. napi_status napi_new_instance(napi_env env,
    2. napi_value cons,
    3. size_t argc,
    4. napi_value* argv,
    5. napi_value* result)
    • [in] env: The environment that the API is invoked under.
    • [in] cons: napi_value representing the JavaScript function to be invoked as a constructor.
    • [in] argc: The count of elements in the argv array.
    • [in] argv: Array of JavaScript values as napi_value representing the arguments to the constructor.
    • [out] result: napi_value representing the JavaScript object returned, which in this case is the constructed object.

    This method is used to instantiate a new JavaScript value using a given napi_value that represents the constructor for the object. For example, consider the following snippet:

    1. function MyObject(param) {
    2. this.param = param;
    3. }
    4. const arg = 'hello';
    5. const value = new MyObject(arg);

    The following can be approximated in N-API using the following snippet:

    1. // Get the constructor function MyObject
    2. napi_value global, constructor, arg, value;
    3. napi_status status = napi_get_global(env, &global);
    4. if (status != napi_ok) return;
    5. status = napi_get_named_property(env, global, "MyObject", &constructor);
    6. if (status != napi_ok) return;
    7. // const arg = "hello"
    8. status = napi_create_string_utf8(env, "hello", NAPI_AUTO_LENGTH, &arg);
    9. if (status != napi_ok) return;
    10. napi_value* argv = &arg;
    11. size_t argc = 1;
    12. // const value = new MyObject(arg)
    13. status = napi_new_instance(env, constructor, argc, argv, &value);

    Returns napi_ok if the API succeeded.