1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-05-24 00:55:06 +00:00

LibJS: Add a mechanism for callback-based object properties

This patch adds NativeProperty, which can be used to implement object
properties that have C++ getters and/or setters.

Use this to move String.prototype.length to its correct place. :^)
This commit is contained in:
Andreas Kling 2020-03-15 18:15:44 +01:00
parent bb57bc1b42
commit 3163929990
7 changed files with 125 additions and 2 deletions

View file

@ -28,6 +28,7 @@
#include <LibJS/Heap.h>
#include <LibJS/Interpreter.h>
#include <LibJS/NativeFunction.h>
#include <LibJS/NativeProperty.h>
#include <LibJS/Object.h>
#include <LibJS/Value.h>
@ -47,8 +48,11 @@ Value Object::get(String property_name) const
const Object* object = this;
while (object) {
auto value = object->m_properties.get(property_name);
if (value.has_value())
if (value.has_value()) {
if (value.value().is_object() && value.value().as_object()->is_native_property())
return static_cast<const NativeProperty*>(value.value().as_object())->get(const_cast<Object*>(this));
return value.value();
}
object = object->prototype();
}
return js_undefined();
@ -64,6 +68,11 @@ void Object::put_native_function(String property_name, AK::Function<Value(Interp
put(property_name, heap().allocate<NativeFunction>(move(native_function)));
}
void Object::put_native_property(String property_name, AK::Function<Value(Object*)> getter, AK::Function<void(Object*, Value)> setter)
{
put(property_name, heap().allocate<NativeProperty>(move(getter), move(setter)));
}
void Object::visit_children(Cell::Visitor& visitor)
{
Cell::visit_children(visitor);