Skip to content

Commit

Permalink
Added methods to add inherited and static properties to classes
Browse files Browse the repository at this point in the history
  • Loading branch information
HalidOdat committed Aug 21, 2020
1 parent be59c4c commit e4d3dac
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
13 changes: 12 additions & 1 deletion boa/examples/classes.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use boa::{
builtins::{
object::{Class, ClassBuilder},
property::Attribute,
value::Value,
},
exec::Interpreter,
Expand Down Expand Up @@ -60,6 +61,12 @@ impl Class for Person {
}
Ok(false.into())
});
class.property("inheritedProperty", 10, Attribute::default());
class.static_property(
"staticProperty",
"Im a static property",
Attribute::WRITABLE | Attribute::ENUMERABLE | Attribute::PERMANENT,
);

Ok(())
}
Expand All @@ -83,7 +90,11 @@ fn main() {
if (!Person.is('Hello')) {
console.log('\'Hello\' string is not a Person class instance.');
}
",
console.log(Person.staticProperty);
console.log(person.inheritedProperty);
console.log(Person.prototype.inheritedProperty === person.inheritedProperty);
",
)
.unwrap();
}
34 changes: 34 additions & 0 deletions boa/src/builtins/object/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,40 @@ impl<'context> ClassBuilder<'context> {
.insert_field(name, Value::from(function));
}

/// Add a property to the class, with the specified attribute.
///
/// It is added to `prototype`.
#[inline]
pub fn property<K, V>(&mut self, key: K, value: V, attribute: Attribute)
where
K: Into<PropertyKey>,
V: Into<Value>,
{
// We bitwise or (`|`) with `Attribute::default()` (`READONLY | NON_ENUMERABLE | PERMANENT`)
// so we dont get an empty attribute.
let property = Property::data_descriptor(value.into(), attribute | Attribute::default());
self.prototype
.borrow_mut()
.insert_property(key.into(), property);
}

/// Add a static property to the class, with the specified attribute.
///
/// It is added to class object itself.
#[inline]
pub fn static_property<K, V>(&mut self, key: K, value: V, attribute: Attribute)
where
K: Into<PropertyKey>,
V: Into<Value>,
{
// We bitwise or (`|`) with `Attribute::default()` (`READONLY | NON_ENUMERABLE | PERMANENT`)
// so we dont get an empty attribute.
let property = Property::data_descriptor(value.into(), attribute | Attribute::default());
self.object
.borrow_mut()
.insert_property(key.into(), property);
}

pub fn context(&mut self) -> &'_ mut Interpreter {
self.context
}
Expand Down

0 comments on commit e4d3dac

Please sign in to comment.