js_name = blah
js_name
屬性可用於綁定到 JavaScript 中與 Rust 中定義的識別符不同的函式。
最常見的用途是將駝峰式大小寫的 JavaScript 識別符轉換為蛇式大小寫的 Rust 識別符
#![allow(unused)] 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)] fn main() { #[wasm_bindgen] extern "C" { #[wasm_bindgen(js_name = "$$$")] fn cash_money() -> u32; } }
但是,您也可以使用 js_name
為多型 JavaScript 函式定義多個簽名
#![allow(unused)] 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)] 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; } }
在 JavaScript 模組使用 export default
的情況下,也可以使用 js_name
屬性。在這種情況下,將 type
宣告上的 js_name
屬性設定為 "default",並將匯出物件上的任何方法的 js_class
屬性 設定為 "default",將會產生正確的匯入。
例如,一個在 JavaScript 中直接匯入的模組
import Foo from "bar";
let f = new Foo();
可以使用 Rust 中的此定義來存取
#![allow(unused)] 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; } }