ClrFunctionInstance.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System;
  2. using Jint.Native;
  3. using Jint.Native.Function;
  4. using Jint.Runtime.Descriptors;
  5. namespace Jint.Runtime.Interop
  6. {
  7. /// <summary>
  8. /// Wraps a Clr method into a FunctionInstance
  9. /// </summary>
  10. public sealed class ClrFunctionInstance : FunctionInstance, IEquatable<ClrFunctionInstance>
  11. {
  12. internal readonly Func<JsValue, JsValue[], JsValue> _func;
  13. public ClrFunctionInstance(
  14. Engine engine,
  15. string name,
  16. Func<JsValue, JsValue[], JsValue> func,
  17. int length = 0,
  18. PropertyFlag lengthFlags = PropertyFlag.AllForbidden)
  19. : base(engine, !string.IsNullOrWhiteSpace(name) ? new JsString(name) : null)
  20. {
  21. _func = func;
  22. _prototype = engine.Function.PrototypeObject;
  23. _length = lengthFlags == PropertyFlag.AllForbidden
  24. ? PropertyDescriptor.AllForbiddenDescriptor.ForNumber(length)
  25. : new PropertyDescriptor(JsNumber.Create(length), lengthFlags);
  26. }
  27. public override JsValue Call(JsValue thisObject, JsValue[] arguments) => _func(thisObject, arguments);
  28. public override bool Equals(JsValue obj)
  29. {
  30. if (ReferenceEquals(null, obj))
  31. {
  32. return false;
  33. }
  34. if (!(obj is ClrFunctionInstance s))
  35. {
  36. return false;
  37. }
  38. return Equals(s);
  39. }
  40. public bool Equals(ClrFunctionInstance other)
  41. {
  42. if (ReferenceEquals(null, other))
  43. {
  44. return false;
  45. }
  46. if (ReferenceEquals(this, other))
  47. {
  48. return true;
  49. }
  50. if (_func == other._func)
  51. {
  52. return true;
  53. }
  54. return false;
  55. }
  56. }
  57. }