constructor

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