| 1 |
# `structural` |
| 2 |
|
| 3 |
> **Note**: As of [RFC 5] this attribute is the default for all imported |
| 4 |
> functions. This attribute is largely ignored today and is only retained for |
| 5 |
> backwards compatibility and learning purposes. |
| 6 |
> |
| 7 |
> The inverse of this attribute, [the `final` |
| 8 |
> attribute](final.html) is more functionally interesting than |
| 9 |
> `structural` (as `structural` is simply the default) |
| 10 |
|
| 11 |
[RFC 5]: https://rustwasm.github.io/rfcs/005-structural-and-deref.html |
| 12 |
|
| 13 |
The `structural` flag can be added to `method` annotations, indicating that the |
| 14 |
method being accessed (or property with getters/setters) should be accessed in a |
| 15 |
structural, duck-type-y fashion. Rather than walking the constructor's prototype |
| 16 |
chain once at load time and caching the property result, the prototype chain is |
| 17 |
dynamically walked on every access. |
| 18 |
|
| 19 |
```rust |
| 20 |
#[wasm_bindgen] |
| 21 |
extern "C" { |
| 22 |
type Duck; |
| 23 |
|
| 24 |
#[wasm_bindgen(method, structural)] |
| 25 |
fn quack(this: &Duck); |
| 26 |
|
| 27 |
#[wasm_bindgen(method, getter, structural)] |
| 28 |
fn is_swimming(this: &Duck) -> bool; |
| 29 |
} |
| 30 |
``` |
| 31 |
|
| 32 |
The constructor for the type here, `Duck`, is not required to exist in |
| 33 |
JavaScript (it's not referenced). Instead `wasm-bindgen` will generate shims |
| 34 |
that will access the passed in JavaScript value's `quack` method or its |
| 35 |
`is_swimming` property. |
| 36 |
|
| 37 |
```js |
| 38 |
// Without `structural`, get the method directly off the prototype at load time: |
| 39 |
const Duck_prototype_quack = Duck.prototype.quack; |
| 40 |
function quack(duck) { |
| 41 |
Duck_prototype_quack.call(duck); |
| 42 |
} |
| 43 |
|
| 44 |
// With `structural`, walk the prototype chain on every access: |
| 45 |
function quack(duck) { |
| 46 |
duck.quack(); |
| 47 |
} |
| 48 |
``` |