js_namespace = blah
此屬性表示 JavaScript 類型是透過給定的命名空間存取的。例如,WebAssembly.Module
API 都是透過 WebAssembly
命名空間存取的。js_namespace
可以應用於任何導入(函式或類型),並且每當產生的 JavaScript 嘗試引用名稱(例如類別或函式名稱)時,都將透過此命名空間存取。
#![allow(unused)] 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)] 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)] 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)] 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 = …
。