BindFunctionInstance.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. private static readonly JsString _name = new JsString("bind");
  9. public BindFunctionInstance(Engine engine)
  10. : base(engine, _name, FunctionThisMode.Global)
  11. {
  12. }
  13. public JsValue TargetFunction { get; set; }
  14. public JsValue BoundThis { get; set; }
  15. public JsValue[] BoundArgs { get; set; }
  16. public override JsValue Call(JsValue thisObject, JsValue[] arguments)
  17. {
  18. if (!(TargetFunction is FunctionInstance f))
  19. {
  20. return ExceptionHelper.ThrowTypeError<ObjectInstance>(Engine);
  21. }
  22. return f.Call(BoundThis, CreateArguments(arguments));
  23. }
  24. public ObjectInstance Construct(JsValue[] arguments, JsValue newTarget)
  25. {
  26. if (!(TargetFunction is IConstructor target))
  27. {
  28. return ExceptionHelper.ThrowTypeError<ObjectInstance>(Engine);
  29. }
  30. return target.Construct(CreateArguments(arguments), newTarget);
  31. }
  32. public override bool HasInstance(JsValue v)
  33. {
  34. var f = TargetFunction.TryCast<FunctionInstance>(x =>
  35. {
  36. ExceptionHelper.ThrowTypeError(Engine);
  37. });
  38. return f.HasInstance(v);
  39. }
  40. private JsValue[] CreateArguments(JsValue[] arguments)
  41. {
  42. return Enumerable.Union(BoundArgs, arguments).ToArray();
  43. }
  44. internal override bool IsConstructor => TargetFunction is IConstructor;
  45. }
  46. }