ClrFunctionInstance.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. private readonly string _name;
  13. internal readonly Func<JsValue, JsValue[], JsValue> _func;
  14. public ClrFunctionInstance(
  15. Engine engine,
  16. string name,
  17. Func<JsValue, JsValue[], JsValue> func,
  18. int length = 0,
  19. PropertyFlag lengthFlags = PropertyFlag.AllForbidden)
  20. : base(engine, !string.IsNullOrWhiteSpace(name) ? new JsString(name) : null)
  21. {
  22. _name = name;
  23. _func = func;
  24. _prototype = engine.Function.PrototypeObject;
  25. _length = lengthFlags == PropertyFlag.AllForbidden
  26. ? PropertyDescriptor.AllForbiddenDescriptor.ForNumber(length)
  27. : new PropertyDescriptor(JsNumber.Create(length), lengthFlags);
  28. }
  29. public override JsValue Call(JsValue thisObject, JsValue[] arguments) => _func(thisObject, arguments);
  30. public override bool Equals(JsValue obj)
  31. {
  32. if (ReferenceEquals(null, obj))
  33. {
  34. return false;
  35. }
  36. if (!(obj is ClrFunctionInstance s))
  37. {
  38. return false;
  39. }
  40. return Equals(s);
  41. }
  42. public bool Equals(ClrFunctionInstance other)
  43. {
  44. if (ReferenceEquals(null, other))
  45. {
  46. return false;
  47. }
  48. if (ReferenceEquals(this, other))
  49. {
  50. return true;
  51. }
  52. if (_func == other._func)
  53. {
  54. return true;
  55. }
  56. return false;
  57. }
  58. public override string ToString()
  59. {
  60. return $"function {_name}() {{ [native code] }}";
  61. }
  62. }
  63. }