constructor
當附加到 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 起不再需要這樣做。