构造函数
当附加到 Rust “构造函数”时,它将使生成的 JavaScript 绑定可作为 new Foo()
调用。
例如,考虑这个导出的 Rust 类型和 constructor
注解
#![allow(unused)] 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)] 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 开始不再需要这样做。