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 = …
。