ArrayConstructor.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using Jint.Native.Function;
  2. using Jint.Native.Object;
  3. using Jint.Runtime;
  4. using Jint.Runtime.Interop;
  5. namespace Jint.Native.Array
  6. {
  7. public sealed class ArrayConstructor : FunctionInstance, IConstructor
  8. {
  9. private ArrayConstructor(Engine engine) : base(engine, null, null, false)
  10. {
  11. }
  12. public ArrayPrototype PrototypeObject { get; private set; }
  13. public static ArrayConstructor CreateArrayConstructor(Engine engine)
  14. {
  15. var obj = new ArrayConstructor(engine);
  16. obj.Extensible = true;
  17. // The value of the [[Prototype]] internal property of the Array constructor is the Function prototype object
  18. obj.Prototype = engine.Function.PrototypeObject;
  19. obj.PrototypeObject = ArrayPrototype.CreatePrototypeObject(engine, obj);
  20. obj.FastAddProperty("length", 1, false, false, false);
  21. // The initial value of Array.prototype is the Array prototype object
  22. obj.FastAddProperty("prototype", obj.PrototypeObject, false, false, false);
  23. return obj;
  24. }
  25. public void Configure()
  26. {
  27. FastAddProperty("isArray", new ClrFunctionInstance(Engine, IsArray, 1), true, false, true);
  28. }
  29. private JsValue IsArray(JsValue thisObj, JsValue[] arguments)
  30. {
  31. if (arguments.Length == 0)
  32. {
  33. return false;
  34. }
  35. var o = arguments.At(0);
  36. return o.IsObject() && o.AsObject().Class == "Array";
  37. }
  38. public override JsValue Call(JsValue thisObject, JsValue[] arguments)
  39. {
  40. return Construct(arguments);
  41. }
  42. public ObjectInstance Construct(JsValue[] arguments)
  43. {
  44. var instance = new ArrayInstance(Engine);
  45. instance.Prototype = PrototypeObject;
  46. instance.Extensible = true;
  47. if (arguments.Length == 1 && arguments.At(0).IsNumber())
  48. {
  49. var length = TypeConverter.ToUint32(arguments.At(0));
  50. if (!TypeConverter.ToNumber(arguments[0]).Equals(length))
  51. {
  52. throw new JavaScriptException(Engine.RangeError);
  53. }
  54. instance.FastAddProperty("length", length, true, false, false);
  55. }
  56. else
  57. {
  58. instance.FastAddProperty("length", 0, true, false, false);
  59. PrototypeObject.Push(instance, arguments);
  60. }
  61. return instance;
  62. }
  63. }
  64. }