napi_new_instance


napi_status napi_new_instance(napi_env env,
                              napi_value cons,
                              size_t argc,
                              napi_value* argv,
                              napi_value* result) 
  • [in] env:调用 API 的环境。

    ¥[in] env: The environment that the API is invoked under.

  • [in] consnapi_value 表示要作为构造函数调用的 JavaScript 函数。

    ¥[in] cons: napi_value representing the JavaScript function to be invoked as a constructor.

  • [in] argcargv 数组中的元素数。

    ¥[in] argc: The count of elements in the argv array.

  • [in] argv:JavaScript 值数组 napi_value 表示构造函数的参数。如果 argc 为零,则可以通过传入 NULL 来省略此参数。

    ¥[in] argv: Array of JavaScript values as napi_value representing the arguments to the constructor. If argc is zero this parameter may be omitted by passing in NULL.

  • [out] resultnapi_value 表示返回的 JavaScript 对象,在本例中是构造的对象。

    ¥[out] result: napi_value representing the JavaScript object returned, which in this case is the constructed object.

此方法用于使用给定的 napi_value 表示对象的构造函数来实例化新的 JavaScript 值。例如,考虑以下片段:

¥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:

function MyObject(param) {
  this.param = param;
}

const arg = 'hello';
const value = new MyObject(arg); 

可以使用以下代码片段在 Node-API 中近似计算以下内容:

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

// Get the constructor function MyObject
napi_value global, constructor, arg, value;
napi_status status = napi_get_global(env, &global);
if (status != napi_ok) return;

status = napi_get_named_property(env, global, "MyObject", &constructor);
if (status != napi_ok) return;

// const arg = "hello"
status = napi_create_string_utf8(env, "hello", NAPI_AUTO_LENGTH, &arg);
if (status != napi_ok) return;

napi_value* argv = &arg;
size_t argc = 1;

// const value = new MyObject(arg)
status = napi_new_instance(env, constructor, argc, argv, &value); 

如果 API 成功,则返回 napi_ok

¥Returns napi_ok if the API succeeded.