Jelajahi Sumber

LibJS: Add Object::invoke()

Linus Groh 5 tahun lalu
induk
melakukan
9755f8d297
2 mengubah file dengan 16 tambahan dan 0 penghapusan
  1. 13 0
      Libraries/LibJS/Runtime/Object.cpp
  2. 3 0
      Libraries/LibJS/Runtime/Object.h

+ 13 - 0
Libraries/LibJS/Runtime/Object.cpp

@@ -662,4 +662,17 @@ Value Object::to_string() const
     return js_string(heap(), String::format("[object %s]", class_name()));
 }
 
+Value Object::invoke(const FlyString& property_name, Optional<MarkedValueList> arguments) const
+{
+    auto& interpreter = const_cast<Object*>(this)->interpreter();
+    auto property = get(property_name).value_or(js_undefined());
+    if (interpreter.exception())
+        return {};
+    if (!property.is_function()) {
+        interpreter.throw_exception<TypeError>(String::format("%s is not a function", property.to_string_without_side_effects().characters()));
+        return {};
+    }
+    return interpreter.call(property.as_function(), const_cast<Object*>(this), move(arguments));
+}
+
 }

+ 3 - 0
Libraries/LibJS/Runtime/Object.h

@@ -31,6 +31,7 @@
 #include <LibJS/Forward.h>
 #include <LibJS/Runtime/Cell.h>
 #include <LibJS/Runtime/IndexedProperties.h>
+#include <LibJS/Runtime/MarkedValueList.h>
 #include <LibJS/Runtime/PrimitiveString.h>
 #include <LibJS/Runtime/PropertyName.h>
 #include <LibJS/Runtime/Shape.h>
@@ -107,6 +108,8 @@ public:
     IndexedProperties& indexed_properties() { return m_indexed_properties; }
     void set_indexed_property_elements(Vector<Value>&& values) { m_indexed_properties = IndexedProperties(move(values)); }
 
+    Value invoke(const FlyString& property_name, Optional<MarkedValueList> arguments = {}) const;
+
 private:
     virtual Value get_by_index(u32 property_index) const;
     virtual bool put_by_index(u32 property_index, Value);