FunctionObject.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Interpreter.h>
  7. #include <LibJS/Runtime/BoundFunction.h>
  8. #include <LibJS/Runtime/FunctionObject.h>
  9. #include <LibJS/Runtime/GlobalObject.h>
  10. namespace JS {
  11. FunctionObject::FunctionObject(Object& prototype)
  12. : Object(prototype)
  13. {
  14. }
  15. FunctionObject::~FunctionObject()
  16. {
  17. }
  18. BoundFunction* FunctionObject::bind(Value bound_this_value, Vector<Value> arguments)
  19. {
  20. auto& vm = this->vm();
  21. FunctionObject& target_function = is<BoundFunction>(*this) ? static_cast<BoundFunction&>(*this).bound_target_function() : *this;
  22. auto get_bound_this_object = [&vm, bound_this_value, this]() -> ThrowCompletionOr<Value> {
  23. if (is<BoundFunction>(*this) && !static_cast<BoundFunction&>(*this).bound_this().is_empty())
  24. return static_cast<BoundFunction&>(*this).bound_this();
  25. switch (bound_this_value.type()) {
  26. case Value::Type::Undefined:
  27. case Value::Type::Null:
  28. if (vm.in_strict_mode())
  29. return bound_this_value;
  30. return &global_object();
  31. default:
  32. return TRY(bound_this_value.to_object(global_object()));
  33. }
  34. };
  35. auto bound_this_object = TRY_OR_DISCARD(get_bound_this_object());
  36. i32 computed_length = 0;
  37. auto length_property = TRY_OR_DISCARD(get(vm.names.length));
  38. if (length_property.is_number())
  39. computed_length = max(0, length_property.as_i32() - static_cast<i32>(arguments.size()));
  40. Object* constructor_prototype = nullptr;
  41. auto prototype_property = TRY_OR_DISCARD(target_function.get(vm.names.prototype));
  42. if (prototype_property.is_object())
  43. constructor_prototype = &prototype_property.as_object();
  44. Vector<Value> all_bound_arguments;
  45. if (is<BoundFunction>(*this))
  46. all_bound_arguments.extend(static_cast<BoundFunction&>(*this).bound_arguments());
  47. all_bound_arguments.extend(move(arguments));
  48. return heap().allocate<BoundFunction>(global_object(), global_object(), target_function, bound_this_object, move(all_bound_arguments), computed_length, constructor_prototype);
  49. }
  50. }