Debian Codegraph @

.cargo/vendor/wasm-bindgen/guide/src/reference/attributes/on-rust-exports/constructor.md

raw
1 # `constructor`
2
3 When attached to a Rust "constructor" it will make the generated JavaScript
4 bindings callable as `new Foo()`.
5
6 For example, consider this exported Rust type and `constructor` annotation:
7
8 ```rust
9 #[wasm_bindgen]
10 pub struct Foo {
11 contents: u32,
12 }
13
14 #[wasm_bindgen]
15 impl Foo {
16 #[wasm_bindgen(constructor)]
17 pub fn new() -> Foo {
18 Foo { contents: 0 }
19 }
20
21 pub fn get_contents(&self) -> u32 {
22 self.contents
23 }
24 }
25 ```
26
27 This can be used in JavaScript as:
28
29 ```js
30 import { Foo } from './my_module';
31
32 const f = new Foo();
33 console.log(f.get_contents());
34 ```
35
36 ## Caveats
37
38 Starting from v0.2.48 there is a bug in `wasm-bindgen` which breaks inheritance of exported Rust structs from JavaScript side (see [#3213](https://github.com/rustwasm/wasm-bindgen/issues/3213)). If you want to inherit from a Rust struct such as:
39
40 ```rust
41 use wasm_bindgen::prelude::*;
42
43 #[wasm_bindgen]
44 pub struct Parent {
45 msg: String,
46 }
47
48 #[wasm_bindgen]
49 impl Parent {
50 #[wasm_bindgen(constructor)]
51 fn new() -> Self {
52 Parent {
53 msg: String::from("Hello from Parent!"),
54 }
55 }
56 }
57 ```
58
59 You will need to reset the prototype of `this` back to the `Child` class prototype after calling the `Parent`'s constructor via `super`.
60
61 ```js
62 import { Parent } from './my_module';
63
64 class Child extends Parent {
65 constructor() {
66 super();
67 Object.setPrototypeOf(this, Child.prototype);
68 }
69 }
70 ```
71
72 This is no longer required as of v0.2.88.