构造函数
当附加到 Rust 的“构造函数”时,它将使生成的 JavaScript 绑定可以像 new Foo()
一样调用。
例如,考虑这个导出的 Rust 类型和 constructor
注解
# #![allow(unused_variables)] #fn main() { #[wasm_bindgen] pub struct Foo { contents: u32, } #[wasm_bindgen] impl Foo { #[wasm_bindgen(constructor)] pub fn new() -> Foo { Foo { contents: 0 } } pub fn get_contents(&self) -> u32 { self.contents } } #}
这可以在 JavaScript 中像这样使用
import { Foo } from './my_module';
const f = new Foo();
console.log(f.get_contents());
注意事项
在 wasm-bindgen
的 >=v0.2.48, <0.2.88
版本中,存在一个错误,该错误会破坏从 JavaScript 端导出的 Rust 结构体的继承(请参阅 #3213)。如果您想从 Rust 结构体(例如)继承
# #![allow(unused_variables)] #fn main() { use wasm_bindgen::prelude::*; #[wasm_bindgen] pub struct Parent { msg: String, } #[wasm_bindgen] impl Parent { #[wasm_bindgen(constructor)] fn new() -> Self { Parent { msg: String::from("Hello from Parent!"), } } } #}
您需要在通过 super
调用 Parent
的构造函数后,将 this
的原型重置回 Child
类的原型。
import { Parent } from './my_module';
class Child extends Parent {
constructor() {
super();
Object.setPrototypeOf(this, Child.prototype);
}
}
从 v0.2.88 开始,不再需要这样做。