[−][src]Module boa::class
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: &Value, args: &[Value], context: &mut Context) -> Result<Self> { // This is equivalent to `String(arg)`. let kind = args.get(0).cloned().unwrap_or_default().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) -> Result<()> { 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(Value::undefined()) }); Ok(()) } }
Structs
ClassBuilder | Class builder which allows adding methods and static methods to the class. |
Traits
Class | Native class. |
ClassConstructor | This is a wrapper around |