CallContext
CallContext
contém todas as informações em uma chamada de função JavaScript.
Arguments
Você pode obter o argumento JavaScript através do método CallContext::get(usize)
:
#[js_function(1)]
fn hey(ctx: CallContext) -> Result<JsUndefined> {
let arg1: JsString = ctx.get(0)?;
ctx.env.get_undefined()
}
A sequência de argumentos começa em 0
, e não pode ser maior do que o número passado na macro js_function
. Se você passar um índice maior do que o número na macro js_function
, um erro JavaScript será lançado.
O tipo do resultado deve ser igual ao tipo real do argumento, ou um erro de tipo será lançado.
struct Native {
value: i32,
}
#[js_function(1)]
fn attach_native_object(ctx: CallContext) -> Result<JsUndefined> {
let count: i32 = ctx.get::<JsNumber>(0)?.try_into()?;
let mut this: JsObject = ctx.this_unchecked();
ctx
.env
.wrap(&mut this, Native { value: count + 100 })?;
ctx.env.get_undefined()
}
#[js_function(1)]
fn get_native_object(ctx: CallContext) -> Result<JsNumber> {
let count: i32 = ctx.get::<JsNumber>(0)?.try_into()?;
let mut this: JsObject = ctx.this_unchecked();
let native: Native = ctx
.env
.unrwap(&mut this)?;
ctx.env.create_int32(native.value + 1)
}
const obj = {
attach: attachNativeObject,
get: getNativeObject,
}
obj.attach(100)
obj.get() // 101
Argument length
O número que foi passado para js_function
é a capacidade do Array de argumentos, o tamanho real dos argumentos pode ser obtido com CallContext::length
.
#[js_function(100)]
fn hey(ctx: CallContext) -> Result<JsUndefined> {
println!("{}", ctx.length);
ctx.env.get_undefined()
}
hey() // 0
hey({}) // 1
This
Você pode obter this object através de CallContext::this
ou CallContext::this_unchecked
. A única diferença entre os dois métodos é que CallContext::this
fará uma verificação de tipo; se o tipo fornecido não corresponder ao this
, um erro InvalidArg
será lançado.
new target
Se a função foi chamada pelo operador new
, você pode usar CallContext::get_new_target
para obter o novo destino dessa função construtora.