napi_define_class


napi_status napi_define_class(napi_env env,
                              const char* utf8name,
                              size_t length,
                              napi_callback constructor,
                              void* data,
                              size_t property_count,
                              const napi_property_descriptor* properties,
                              napi_value* result); 
  • [in] env:调用该 API 时所处的环境。
  • [in] utf8name:JavaScript 构造函数的名称。为了清晰起见,建议在封装 C++ 类时使用 C++ 类名。
  • [in] lengthutf8name 的字节长度,如果是以 null 结尾,则为 NAPI_AUTO_LENGTH
  • [in] 构造函数:处理类实例构造的回调函数。在封装 C++ 类时,该方法必须是具有 napi_callback 签名的静态成员。不能使用 C++ 类构造函数。napi_callback 提供了更多细节。
  • [in] data:可选数据,将作为回调信息的 data 属性传递给构造函数回调。
  • [in] property_countproperties 数组参数中的项目数量。
  • [in] properties:描述类上的静态和实例数据属性、访问器以及方法的属性描述符数组。参见 napi_property_descriptor
  • [out] result:表示该类构造函数的 napi_value

如果 API 成功,则返回 napi_ok

【Returns napi_ok if the API succeeded.】

定义一个 JavaScript 类,包括:

【Defines a JavaScript class, including:】

  • 一个具有类名的 JavaScript 构造函数。当封装相应的 C++ 类时,通过 constructor 传递的回调可以用来实例化一个新的 C++ 类实例,然后可以使用 napi_wrap 将其放入正在构建的 JavaScript 对象实例中。
  • 构造函数上的属性,其实现可以调用 C++ 类的相应 静态 数据属性、访问器和方法(通过带有 napi_static 属性的属性描述符定义)。
  • 构造函数 prototype 对象上的属性。在封装 C++ 类时,可以在属性描述符中提供的静态函数中调用 C++ 类的 非静态 数据属性、访问器和方法(前提是这些属性描述符没有 napi_static 属性),方法是通过使用 napi_unwrap 获取放置在 JavaScript 对象实例中的 C++ 类实例。

在封装一个 C++ 类时,通过 constructor 传递的 C++ 构造函数回调应该是类上的一个静态方法,该方法调用实际的类构造函数,然后将新的 C++ 实例封装到一个 JavaScript 对象中,并返回这个封装对象。详情见 napi_wrap

【When wrapping a C++ class, the C++ constructor callback passed via constructor should be a static method on the class that calls the actual class constructor, then wraps the new C++ instance in a JavaScript object, and returns the wrapper object. See napi_wrap for details.】

napi_define_class 返回的 JavaScript 构造函数通常会被保存,并在稍后用于从原生代码构造该类的新实例,和/或检查提供的值是否为该类的实例。在这种情况下,为了防止该函数值被垃圾回收,可以使用 napi_create_reference 创建对它的强持久引用,从而确保引用计数保持 >= 1。

【The JavaScript constructor function returned from napi_define_class is often saved and used later to construct new instances of the class from native code, and/or to check whether provided values are instances of the class. In that case, to prevent the function value from being garbage-collected, a strong persistent reference to it can be created using napi_create_reference, ensuring that the reference count is kept >= 1.】

通过 data 参数或 napi_property_descriptor 数组项的 data 字段传递给此 API 的任何非 NULL 数据都可以与生成的 JavaScript 构造函数(返回在 result 参数中)关联,并且可以在类被垃圾回收时通过将 JavaScript 函数和数据一起传递给 napi_add_finalizer 来释放。

【Any non-NULL data which is passed to this API via the data parameter or via the data field of the napi_property_descriptor array items can be associated with the resulting JavaScript constructor (which is returned in the result parameter) and freed whenever the class is garbage-collected by passing both the JavaScript function and the data to napi_add_finalizer.】