Expand description
Traits and structs for implementing native classes.
Native classes are implemented through the Class
trait.
// This does not have to be an enum it can also be a struct.
#[derive(Debug, Trace, Finalize)]
enum Animal {
Cat,
Dog,
Other,
}
impl Class for Animal {
// we set the binging name of this function to be `"Animal"`.
const NAME: &'static str = "Animal";
// We set the length to `1` since we accept 1 arguments in the constructor.
const LENGTH: usize = 1;
// This is what is called when we do `new Animal()`
fn constructor(_this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<Self> {
// This is equivalent to `String(arg)`.
let kind = args.get_or_undefined(0).to_string(context)?;
let animal = match kind.as_str() {
"cat" => Self::Cat,
"dog" => Self::Dog,
_ => Self::Other,
};
Ok(animal)
}
/// This is where the object is intitialized.
fn init(class: &mut ClassBuilder) -> JsResult<()> {
class.method("speak", 0, |this, _args, _ctx| {
if let Some(object) = this.as_object() {
if let Some(animal) = object.downcast_ref::<Animal>() {
match &*animal {
Self::Cat => println!("meow"),
Self::Dog => println!("woof"),
Self::Other => println!(r"¯\_(ツ)_/¯"),
}
}
}
Ok(JsValue::undefined())
});
Ok(())
}
}
Structs
Class builder which allows adding methods and static methods to the class.
Traits
Native class.
This is a wrapper around
Class::constructor
that sets the internal data of a class.