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 中绑定命名空间项的示例。logFoo::new 函数将在 Rust 模块中可用,并且将在 JavaScript 中作为 console.lognew 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 = …