| 1 |
# `inspectable` |
| 2 |
|
| 3 |
By default, structs exported from Rust become JavaScript classes with a single `ptr` property. All other properties are implemented as getters, which are not displayed when calling `toJSON`. |
| 4 |
|
| 5 |
The `inspectable` attribute can be used on Rust structs to provide a `toJSON` and `toString` implementation that display all readable fields. For example: |
| 6 |
|
| 7 |
```rust |
| 8 |
#[wasm_bindgen(inspectable)] |
| 9 |
pub struct Baz { |
| 10 |
pub field: i32, |
| 11 |
private: i32, |
| 12 |
} |
| 13 |
|
| 14 |
#[wasm_bindgen] |
| 15 |
impl Baz { |
| 16 |
#[wasm_bindgen(constructor)] |
| 17 |
pub fn new(field: i32) -> Baz { |
| 18 |
Baz { field, private: 13 } |
| 19 |
} |
| 20 |
} |
| 21 |
``` |
| 22 |
|
| 23 |
Provides the following behavior as in this JavaScript snippet: |
| 24 |
|
| 25 |
```js |
| 26 |
const obj = new Baz(3); |
| 27 |
assert.deepStrictEqual(obj.toJSON(), { field: 3 }); |
| 28 |
obj.field = 4; |
| 29 |
assert.strictEqual(obj.toString(), '{"field":4}'); |
| 30 |
``` |
| 31 |
|
| 32 |
One or both of these implementations can be overridden as desired. Note that the generated `toString` calls `toJSON` internally, so overriding `toJSON` will affect its output as a side effect. |
| 33 |
|
| 34 |
```rust |
| 35 |
#[wasm_bindgen] |
| 36 |
impl Baz { |
| 37 |
#[wasm_bindgen(js_name = toJSON)] |
| 38 |
pub fn to_json(&self) -> i32 { |
| 39 |
self.field |
| 40 |
} |
| 41 |
|
| 42 |
#[wasm_bindgen(js_name = toString)] |
| 43 |
pub fn to_string(&self) -> String { |
| 44 |
format!("Baz: {}", self.field) |
| 45 |
} |
| 46 |
} |
| 47 |
``` |
| 48 |
|
| 49 |
Note that the output of `console.log` will remain unchanged and display only the `ptr` field in browsers. It is recommended to call `toJSON` or `JSON.stringify` in these situations to aid with logging or debugging. Node.js does not suffer from this limitation, see the section below. |
| 50 |
|
| 51 |
## `inspectable` Classes in Node.js |
| 52 |
|
| 53 |
When the `nodejs` target is used, an additional `[util.inspect.custom]` implementation is provided which calls `toJSON` internally. This method is used for `console.log` and similar functions to display all readable fields of the Rust struct. |