FunctionObject.cpp 2.2 KB

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