使用 JavaScript 函数
¥Working with JavaScript functions
Node-API 提供了一组 API,允许 JavaScript 代码回调原生代码。支持回调原生代码的 Node-API 接受由 napi_callback
类型表示的回调函数。当 JavaScript VM 回调原生代码时,将调用提供的 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:
-
获取有关调用回调的上下文的信息。
¥Get information about the context in which the callback was invoked.
-
获取传递给回调的参数。
¥Get the arguments passed into the callback.
-
从回调中返回
napi_value
。¥Return a
napi_value
back from the callback.
此外,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
.