ArrayConstructor.cs 2.6 KB

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