Struct neon::types::JsFunction[][src]

#[repr(C)]
pub struct JsFunction<T: Object = JsObject> { /* fields omitted */ }
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

Create a CallOptions for calling this function.

Create a ConstructOptions for calling this function as a constructor.

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

This is supported 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

Performs the conversion.

Performs the conversion.

The resulting type after obtaining ownership.

Creates owned data from borrowed data, usually by cloning. Read more

🔬 This is a nightly-only experimental API. (toowned_clone_into)

Uses borrowed data to replace owned data, usually by cloning. Read more

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.