js_name = blah

js_name 屬性可用於繫結到 JavaScript 中與 Rust 中定義的識別符不同的函式。

最常見的情況是將駝峰式 JavaScript 識別符轉換為蛇式 Rust 識別符


# #![allow(unused_variables)]
#fn main() {
#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(js_name = jsOftenUsesCamelCase)]
    fn js_often_uses_camel_case() -> u32;
}
#}

有時,它用於繫結到不是有效的 Rust 識別符的 JavaScript 識別符,在這種情況下,會使用 js_name = "some string" 而不是 js_name = ident


# #![allow(unused_variables)]
#fn main() {
#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(js_name = "$$$")]
    fn cash_money() -> u32;
}
#}

但是,您也可以使用 js_name 為多型的 JavaScript 函式定義多個簽名


# #![allow(unused_variables)]
#fn main() {
#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(js_namespace = console, js_name = log)]
    fn console_log_str(s: &str);

    #[wasm_bindgen(js_namespace = console, js_name = log)]
    fn console_log_u32(n: u32);

    #[wasm_bindgen(js_namespace = console, js_name = log)]
    fn console_log_many(a: u32, b: &JsValue);
}
#}

所有這些函式都會在 JavaScript 中呼叫 console.log,但每個識別符在 Rust 中只會有一個簽名。

請注意,如果在匯入類型時使用 js_name,則在定義類型的方法時,也需要使用js_class 屬性


# #![allow(unused_variables)]
#fn main() {
#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(js_name = String)]
    type JsString;
    #[wasm_bindgen(method, getter, js_class = "String")]
    pub fn length(this: &JsString) -> u32;
}
#}

js_name 屬性也可以用於 JavaScript 模組使用 export default 的情況。 在這種情況下,將 type 宣告上的 js_name 屬性設定為 "default",並將匯出物件上的任何方法的 js_class 屬性設定為 "default",將會產生正確的匯入。

例如,可以直接在 JavaScript 中匯入的模組

import Foo from "bar";

let f = new Foo();

可以使用 Rust 中的這個定義來存取


# #![allow(unused_variables)]
#fn main() {
#[wasm_bindgen(module = "bar")]
extern "C" {
    #[wasm_bindgen(js_name = default)]
    type Foo;
    #[wasm_bindgen(constructor, js_class = default)]
    pub fn new() -> Foo;
}
#}