结构化

注意:根据 RFC 5,此属性是所有导入函数的默认属性。 此属性在今天很大程度上被忽略,仅保留用于向后兼容和学习目的。

此属性的反向属性,final 属性在功能上比 structural 更有趣(因为 structural 只是默认值)

structural 标志可以添加到 method 注释中,表明被访问的方法(或带有 getter/setter 的属性)应该以结构化的、鸭子类型的方式访问。 而不是在加载时走一次构造函数的原型链并缓存属性结果,而是在每次访问时动态地遍历原型链。


# #![allow(unused_variables)]
#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();
}