Struct neon::types::JsFunction [−][src]
Expand description
A JavaScript function object.
A JsFunction may come from an existing JavaScript function, for example
by extracting it from the property of another object such as the
global object, or it may be defined in Rust
with JsFunction::new().
Calling functions
Neon provides a convenient syntax for calling JavaScript functions with the
call_with() method, which produces a CallOptions
struct that can be used to provide the function arguments (and optionally, the binding for
this) before calling the function:
// Extract the parseInt function from the global object
let parse_int: Handle<JsFunction> = global
.get(&mut cx, "parseInt")?
.downcast_or_throw(&mut cx)?;
// Call parseInt("42")
let x: Handle<JsNumber> = parse_int
.call_with(&mut cx)
.arg(cx.string("42"))
.apply(&mut cx)?;Calling functions as constructors
A JsFunction can be called as a constructor (like new Array(16) or
new URL("https://neon-bindings.com")) with the
construct_with() method:
// Extract the URL constructor from the global object
let url: Handle<JsFunction> = global
.get(&mut cx, "URL")?
.downcast_or_throw(&mut cx)?;
// Call new URL("https://neon-bindings.com")
let obj = url
.construct_with(&cx)
.arg(cx.string("https://neon-bindings.com"))
.apply(&mut cx)?;Defining functions
JavaScript functions can be defined in Rust with the
JsFunction::new() constructor, which takes
a Rust implementation function and produces a JavaScript function.
// A function implementation that adds 1 to its first argument
fn add1(mut cx: FunctionContext) -> JsResult<JsNumber> {
let x: Handle<JsNumber> = cx.argument(0)?;
let v = x.value(&mut cx);
Ok(cx.number(v + 1.0))
}
// Define a new JsFunction implemented with the add1 function
let f = JsFunction::new(&mut cx, add1)?;Implementations
pub fn new<'a, C, U>(
cx: &mut C,
f: fn(_: FunctionContext<'_>) -> JsResult<'_, U>
) -> JsResult<'a, JsFunction> where
C: Context<'a>,
U: Value,
Create a CallOptions for calling this function.
Create a ConstructOptions for calling this function
as a constructor.
Trait Implementations
fn get<'a, C: Context<'a>, K: PropertyKey>(
self,
cx: &mut C,
key: K
) -> NeonResult<Handle<'a, JsValue>>
fn get<'a, C: Context<'a>, K: PropertyKey>(
self,
cx: &mut C,
key: K
) -> NeonResult<Handle<'a, JsValue>>
napi-1 only.napi-1 and napi-6 only.fn set<'a, C: Context<'a>, K: PropertyKey, W: Value>(
self,
cx: &mut C,
key: K,
val: Handle<'_, W>
) -> NeonResult<bool>
fn set<'a, C: Context<'a>, K: PropertyKey, W: Value>(
self,
cx: &mut C,
key: K,
val: Handle<'_, W>
) -> NeonResult<bool>
napi-1 only.Auto Trait Implementations
impl<T> RefUnwindSafe for JsFunction<T> where
T: RefUnwindSafe,
impl<T = JsObject> !Send for JsFunction<T>
impl<T = JsObject> !Sync for JsFunction<T>
impl<T> Unpin for JsFunction<T> where
T: Unpin,
impl<T> UnwindSafe for JsFunction<T> where
T: UnwindSafe,
Blanket Implementations
Mutably borrows from an owned value. Read more