结构性
注意:根据 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
将生成访问传入的 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();
}