結構性

注意:根據 RFC 5,此屬性是所有匯入函式的預設值。 此屬性目前在很大程度上被忽略,僅為了向後相容性和學習目的而保留。

這個屬性的相反屬性,final 屬性structural 在功能上更有趣(因為 structural 只是預設值)

structural 標誌可以添加到 method 注釋中,表示存取的函式(或具有 getter/setter 的屬性)應該以結構性、鴨子類型的方式存取。 而不是在載入時一次遍歷建構函式的原型鏈並快取屬性結果,而是在每次存取時動態遍歷原型鏈。

#![allow(unused)]
fn main() {
#[wasm_bindgen]
extern "C" {
    type Duck;

    #[wasm_bindgen(method, structural)]
    fn quack(this: &Duck);

    #[wasm_bindgen(method, getter, structural)]
    fn is_swimming(this: &Duck) -> bool;
}
}

此處類型 Duck 的建構函式不需要存在於 JavaScript 中(它沒有被引用)。 相反地,wasm-bindgen 將生成 shims,這些 shims 將存取傳入的 JavaScript 值的 quack 函式或其 is_swimming 屬性。

// Without `structural`, get the method directly off the prototype at load time:
const Duck_prototype_quack = Duck.prototype.quack;
function quack(duck) {
  Duck_prototype_quack.call(duck);
}

// With `structural`, walk the prototype chain on every access:
function quack(duck) {
  duck.quack();
}