BindFunctionInstance.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System.Linq;
  2. using Jint.Native.Object;
  3. using Jint.Runtime;
  4. namespace Jint.Native.Function
  5. {
  6. public sealed class BindFunctionInstance : FunctionInstance, IConstructor
  7. {
  8. public BindFunctionInstance(Engine engine)
  9. : base(engine, "bind", System.ArrayExt.Empty<string>(), null, false)
  10. {
  11. }
  12. public JsValue TargetFunction { get; set; }
  13. public JsValue BoundThis { get; set; }
  14. public JsValue[] BoundArgs { get; set; }
  15. public override JsValue Call(JsValue thisObject, JsValue[] arguments)
  16. {
  17. if (!(TargetFunction is FunctionInstance f))
  18. {
  19. return ExceptionHelper.ThrowTypeError<ObjectInstance>(Engine);
  20. }
  21. return f.Call(BoundThis, CreateArguments(arguments));
  22. }
  23. public ObjectInstance Construct(JsValue[] arguments, JsValue newTarget)
  24. {
  25. if (!(TargetFunction is IConstructor target))
  26. {
  27. return ExceptionHelper.ThrowTypeError<ObjectInstance>(Engine);
  28. }
  29. return target.Construct(CreateArguments(arguments), newTarget);
  30. }
  31. public override bool HasInstance(JsValue v)
  32. {
  33. var f = TargetFunction.TryCast<FunctionInstance>(x =>
  34. {
  35. ExceptionHelper.ThrowTypeError(Engine);
  36. });
  37. return f.HasInstance(v);
  38. }
  39. private JsValue[] CreateArguments(JsValue[] arguments)
  40. {
  41. return Enumerable.Union(BoundArgs, arguments).ToArray();
  42. }
  43. internal override bool IsConstructor => TargetFunction is IConstructor;
  44. }
  45. }