NumberConstructor.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using Jint.Native.Function;
  2. using Jint.Native.Object;
  3. using Jint.Runtime;
  4. using Jint.Runtime.Descriptors;
  5. namespace Jint.Native.Number
  6. {
  7. public sealed class NumberConstructor : FunctionInstance, IConstructor
  8. {
  9. public NumberConstructor(Engine engine)
  10. : base(engine, "Number", null, null, false)
  11. {
  12. }
  13. public static NumberConstructor CreateNumberConstructor(Engine engine)
  14. {
  15. var obj = new NumberConstructor(engine);
  16. obj.Extensible = true;
  17. // The value of the [[Prototype]] internal property of the Number constructor is the Function prototype object
  18. obj.Prototype = engine.Function.PrototypeObject;
  19. obj.PrototypeObject = NumberPrototype.CreatePrototypeObject(engine, obj);
  20. obj.SetOwnProperty("length", new PropertyDescriptor(1, PropertyFlag.AllForbidden));
  21. // The initial value of Number.prototype is the Number prototype object
  22. obj.SetOwnProperty("prototype", new PropertyDescriptor(obj.PrototypeObject, PropertyFlag.AllForbidden));
  23. return obj;
  24. }
  25. public void Configure()
  26. {
  27. SetOwnProperty("MAX_VALUE", new PropertyDescriptor(double.MaxValue, PropertyFlag.AllForbidden));
  28. SetOwnProperty("MIN_VALUE", new PropertyDescriptor(double.Epsilon, PropertyFlag.AllForbidden));
  29. SetOwnProperty("NaN", new PropertyDescriptor(double.NaN, PropertyFlag.AllForbidden));
  30. SetOwnProperty("NEGATIVE_INFINITY", new PropertyDescriptor(double.NegativeInfinity, PropertyFlag.AllForbidden));
  31. SetOwnProperty("POSITIVE_INFINITY", new PropertyDescriptor(double.PositiveInfinity, PropertyFlag.AllForbidden));
  32. SetOwnProperty("EPSILON", new PropertyDescriptor(JsNumber.JavaScriptEpsilon, PropertyFlag.AllForbidden));
  33. }
  34. public override JsValue Call(JsValue thisObject, JsValue[] arguments)
  35. {
  36. if (arguments.Length == 0)
  37. {
  38. return 0d;
  39. }
  40. return TypeConverter.ToNumber(arguments[0]);
  41. }
  42. /// <summary>
  43. /// http://www.ecma-international.org/ecma-262/5.1/#sec-15.7.2.1
  44. /// </summary>
  45. /// <param name="arguments"></param>
  46. /// <returns></returns>
  47. public ObjectInstance Construct(JsValue[] arguments)
  48. {
  49. return Construct(arguments.Length > 0 ? TypeConverter.ToNumber(arguments[0]) : 0);
  50. }
  51. public NumberPrototype PrototypeObject { get; private set; }
  52. public NumberInstance Construct(double value)
  53. {
  54. return Construct(JsNumber.Create(value));
  55. }
  56. public NumberInstance Construct(JsNumber value)
  57. {
  58. var instance = new NumberInstance(Engine)
  59. {
  60. Prototype = PrototypeObject,
  61. NumberData = value,
  62. Extensible = true
  63. };
  64. return instance;
  65. }
  66. }
  67. }