ErrorConstructor.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using Jint.Native.Function;
  2. using Jint.Native.Object;
  3. using Jint.Runtime;
  4. using Jint.Runtime.Descriptors;
  5. namespace Jint.Native.Error
  6. {
  7. public sealed class ErrorConstructor : FunctionInstance, IConstructor
  8. {
  9. private JsString _name;
  10. private static readonly JsString _functionName = new JsString("Error");
  11. public ErrorConstructor(Engine engine) : base(engine, _functionName)
  12. {
  13. }
  14. public static ErrorConstructor CreateErrorConstructor(Engine engine, JsString name)
  15. {
  16. var obj = new ErrorConstructor(engine)
  17. {
  18. _name = name,
  19. _prototype = engine.Function.PrototypeObject
  20. };
  21. // The value of the [[Prototype]] internal property of the Error constructor is the Function prototype object (15.11.3)
  22. obj.PrototypeObject = ErrorPrototype.CreatePrototypeObject(engine, obj, name);
  23. obj._length = PropertyDescriptor.AllForbiddenDescriptor.NumberOne;
  24. // The initial value of Error.prototype is the Error prototype object
  25. obj._prototypeDescriptor = new PropertyDescriptor(obj.PrototypeObject, PropertyFlag.AllForbidden);
  26. return obj;
  27. }
  28. public override JsValue Call(JsValue thisObject, JsValue[] arguments)
  29. {
  30. return Construct(arguments, thisObject);
  31. }
  32. public ObjectInstance Construct(JsValue[] arguments)
  33. {
  34. return Construct(arguments, this);
  35. }
  36. public ObjectInstance Construct(JsValue[] arguments, JsValue newTarget)
  37. {
  38. var o = OrdinaryCreateFromConstructor(
  39. newTarget,
  40. PrototypeObject,
  41. static (e, state) => new ErrorInstance(e, (JsString) state),
  42. _name);
  43. var jsValue = arguments.At(0);
  44. if (!jsValue.IsUndefined())
  45. {
  46. var msg = TypeConverter.ToString(jsValue);
  47. var msgDesc = new PropertyDescriptor(msg, true, false, true);
  48. o.DefinePropertyOrThrow("message", msgDesc);
  49. }
  50. return o;
  51. }
  52. public ErrorPrototype PrototypeObject { get; private set; }
  53. protected internal override ObjectInstance GetPrototypeOf()
  54. {
  55. return _name._value != "Error" ? _engine.Error : _prototype;
  56. }
  57. }
  58. }