Debian Codegraph @

.cargo/vendor/wasm-bindgen/guide/src/web-sys/inheritance.md

raw
1 # Inheritance in `web-sys`
2
3 Inheritance between JS classes is the bread and butter of how the DOM works on
4 the web, and as a result it's quite important for `web-sys` to provide access to
5 this inheritance hierarchy as well! There are few ways you can access the
6 inheritance hierarchy when using `web-sys`.
7
8 ### Accessing parent classes using `Deref`
9
10 Like smart pointers in Rust, all types in `web_sys` implement `Deref` to their
11 parent JS class. This means, for example, if you have a `web_sys::Element` you
12 can create a `web_sys::Node` from that implicitly:
13
14 ```rust
15 let element: &Element = ...;
16
17 element.append_child(..); // call a method on `Node`
18
19 method_expecting_a_node(&element); // coerce to `&Node` implicitly
20
21 let node: &Node = &element; // explicitly coerce to `&Node`
22 ```
23
24 Using `Deref` allows ergonomic transitioning up the inheritance hierarchy to the
25 parent class and beyond, giving you access to all the methods using the `.`
26 operator.
27
28 ### Accessing parent classes using `AsRef`
29
30 In addition to `Deref`, the `AsRef` trait is implemented for all types in
31 `web_sys` for all types in the inheritance hierarchy. For example for the
32 `HtmlAnchorElement` type you'll find:
33
34 ```rust
35 impl AsRef<HtmlElement> for HtmlAnchorElement
36 impl AsRef<Element> for HtmlAnchorElement
37 impl AsRef<Node> for HtmlAnchorElement
38 impl AsRef<EventTarget> for HtmlAnchorElement
39 impl AsRef<Object> for HtmlAnchorElement
40 impl AsRef<JsValue> for HtmlAnchorElement
41 ```
42
43 You can use `.as_ref()` to explicitly get a reference to any parent class from
44 from a type in `web_sys`. Note that because of the number of `AsRef`
45 implementations you'll likely need to have type inference guidance as well.
46
47 ### Accessing child clases using `JsCast`
48
49 Finally the `wasm_bindgen::JsCast` trait can be used to implement all manner of
50 casts between types. It supports static unchecked casts between types as well as
51 dynamic runtime-checked casts (using `instanceof`) between types.
52
53 More documentation about this can be found [on the trait itself][jscast]
54
55 [jscast]: https://docs.rs/wasm-bindgen/0.2/wasm_bindgen/trait.JsCast.html