Struct neon::types::JsFunction

source ·
#[repr(transparent)]
pub struct JsFunction<T: Object = JsObject> { /* private fields */ }
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")?;

// 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")?;

// 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§

Create a CallOptions for calling this function.

Create a ConstructOptions for calling this function as a constructor.

Trait Implementations§

Formats the value using the given formatter. Read more
Gets a property from a JavaScript object that may be undefined and attempts to downcast the value if it existed. Read more
Gets a property from a JavaScript object as a JsValue. Read more
Gets a property from a JavaScript object and attempts to downcast as a specific type. Equivalent to calling obj.get_value(&mut cx)?.downcast_or_throw(&mut cx). Read more
Available on crate feature napi-6 only.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.