結構式
注意:自 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
將產生 shim,該 shim 將存取傳入的 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();
}