FunctionObject.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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 bound_this_object = [&vm, bound_this_value, this]() -> 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 bound_this_value.to_object(global_object());
  33. }
  34. }();
  35. i32 computed_length = 0;
  36. auto length_property = TRY_OR_DISCARD(get(vm.names.length));
  37. if (length_property.is_number())
  38. computed_length = max(0, length_property.as_i32() - static_cast<i32>(arguments.size()));
  39. Object* constructor_prototype = nullptr;
  40. auto prototype_property = TRY_OR_DISCARD(target_function.get(vm.names.prototype));
  41. if (prototype_property.is_object())
  42. constructor_prototype = &prototype_property.as_object();
  43. Vector<Value> all_bound_arguments;
  44. if (is<BoundFunction>(*this))
  45. all_bound_arguments.extend(static_cast<BoundFunction&>(*this).bound_arguments());
  46. all_bound_arguments.extend(move(arguments));
  47. return heap().allocate<BoundFunction>(global_object(), global_object(), target_function, bound_this_object, move(all_bound_arguments), computed_length, constructor_prototype);
  48. }
  49. }