Debian Codegraph @

.cargo/vendor/wasm-bindgen/guide/src/reference/attributes/on-js-imports/getter-and-setter.md

raw
1 # `getter` and `setter`
2
3 These two attributes can be combined with `method` to indicate that this is a
4 getter or setter method. A `getter`-tagged function by default accesses the
5 JavaScript property with the same name as the getter function. A `setter`'s
6 function name is currently required to start with `set_` and the property it
7 accesses is the suffix after `set\_`.
8
9 Consider the following JavaScript class that has a getter and setter for the
10 `white_russians` property:
11
12 ```js
13 class TheDude {
14 get white_russians() {
15 ...
16 }
17 set white_russians(val) {
18 ...
19 }
20 }
21 ```
22
23 We would import this with the following `#[wasm_bindgen]` attributes:
24
25 ```rust
26 #[wasm_bindgen]
27 extern "C" {
28 type TheDude;
29
30 #[wasm_bindgen(method, getter)]
31 fn white_russians(this: &TheDude) -> u32;
32
33 #[wasm_bindgen(method, setter)]
34 fn set_white_russians(this: &TheDude, val: u32);
35 }
36 ```
37
38 Here we're importing the `TheDude` type and defining the ability to access each
39 object's `white_russians` property. The first function here is a getter and will
40 be available in Rust as `the_dude.white_russians()`, and the latter is the
41 setter which is accessible as `the_dude.set_white_russians(2)`. Note that both
42 functions have a `this` argument as they're tagged with `method`.
43
44 Finally, you can also pass an argument to the `getter` and `setter`
45 properties to configure what property is accessed. When the property is
46 explicitly specified then there is no restriction on the method name. For
47 example the below is equivalent to the above:
48
49 ```rust
50 #[wasm_bindgen]
51 extern "C" {
52 type TheDude;
53
54 #[wasm_bindgen(method, getter = white_russians)]
55 fn my_custom_getter_name(this: &TheDude) -> u32;
56
57 #[wasm_bindgen(method, setter = white_russians)]
58 fn my_custom_setter_name(this: &TheDude, val: u32);
59 }
60 ```
61
62 Heads up! `getter` and `setter` functions are found on the constructor's
63 prototype chain once at load time, cached, and then the cached accessor is
64 invoked on each access. If you need to dynamically walk the prototype chain on
65 every access, add the `structural` attribute!
66
67 ```js
68 // This is the default function Rust will invoke on `the_dude.white_russians()`:
69 const white_russians = Object.getOwnPropertyDescriptor(
70 TheDude.prototype,
71 "white_russians"
72 ).get;
73
74 // This is what you get by adding `structural`:
75 const white_russians = function(the_dude) {
76 return the_dude.white_russians;
77 };
78 ```