使用 JavaScript 函数


【Working with JavaScript functions】

Node-API 提供了一组 API,允许 JavaScript 代码回调到原生代码。支持回调到原生代码的 Node-API 接受由 napi_callback 类型表示的回调函数。当 JavaScript 虚拟机回调到原生代码时,会调用提供的 napi_callback 函数。本节中记录的 API 允许回调函数执行以下操作:

【Node-API provides a set of APIs that allow JavaScript code to call back into native code. Node-APIs that support calling back into native code take in a callback functions represented by the napi_callback type. When the JavaScript VM calls back to native code, the napi_callback function provided is invoked. The APIs documented in this section allow the callback function to do the following:】

  • 获取有关回调被调用的上下文信息。
  • 获取传入回调的参数。
  • 从回调函数返回一个 napi_value

此外,Node-API 提供了一组函数,允许从本地代码调用 JavaScript 函数。可以像普通的 JavaScript 函数调用一样调用函数,也可以作为构造函数调用。

【Additionally, Node-API provides a set of functions which allow calling JavaScript functions from native code. One can either call a function like a regular JavaScript function call, or as a constructor function.】

通过 napi_property_descriptor 项的 data 字段传递给此 API 的任何非 NULL 数据都可以与 object 关联,并在 object 被垃圾回收时释放,方法是将 object 和数据一起传递给 napi_add_finalizer

【Any non-NULL data which is passed to this API via the data field of the napi_property_descriptor items can be associated with object and freed whenever object is garbage-collected by passing both object and the data to napi_add_finalizer.】