js_namespace = blah
這個屬性表示 JavaScript 類型是透過給定的命名空間存取的。例如,WebAssembly.Module
API 都是透過 WebAssembly
命名空間存取的。js_namespace
可以應用於任何導入 (函數或類型),而且每當生成的 JavaScript 嘗試引用名稱(例如類別或函數名稱)時,都會透過這個命名空間存取。
# #![allow(unused_variables)] #fn main() { #[wasm_bindgen] extern "C" { #[wasm_bindgen(js_namespace = console)] fn log(s: &str); type Foo; #[wasm_bindgen(constructor, js_namespace = Bar)] fn new() -> Foo; } log("hello, console!"); Foo::new(); #}
這是一個如何在 Rust 中綁定命名空間項目的範例。 log
和 Foo::new
函數將在 Rust 模組中可用,並在 JavaScript 中以 console.log
和 new Bar.Foo
的形式調用。
也可以存取巢狀命名空間下的 JavaScript 物件。 js_namespace
也接受字串陣列來指定命名空間。
# #![allow(unused_variables)] #fn main() { #[wasm_bindgen] extern "C" { #[wasm_bindgen(js_namespace = ["window", "document"])] fn write(s: &str); } write("hello, document!"); #}
此範例展示如何在 Rust 中綁定 window.document.write
。
如果 extern "C" { … }
區塊中的所有項目都具有相同的 js_namespace = …
# #![allow(unused_variables)] #fn main() { #[wasm_bindgen] extern "C" { #[wasm_bindgen(js_namespace = Math)] fn random() -> f64; #[wasm_bindgen(js_namespace = Math)] fn log(a: f64) -> f64; // ... } #}
那麼該巨集參數也可以移到外層區塊
# #![allow(unused_variables)] #fn main() { #[wasm_bindgen(js_namespace = Math)] extern "C" { #[wasm_bindgen] fn random() -> f64; #[wasm_bindgen] fn log(a: f64) -> f64; // ... } #}
個別項目的 js_namespace = …
優先於外層區塊的 js_namespace = …
。