ArrayConstructor.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System;
  2. using Jint.Native.Function;
  3. using Jint.Native.Object;
  4. using Jint.Runtime.Descriptors;
  5. using Jint.Runtime.Interop;
  6. namespace Jint.Native.Array
  7. {
  8. public sealed class ArrayConstructor : FunctionInstance, IConstructor
  9. {
  10. private readonly Engine _engine;
  11. public ArrayConstructor(Engine engine) : base(engine, new ObjectInstance(engine.RootFunction), null, null)
  12. {
  13. _engine = engine;
  14. // the constructor is the function constructor of an object
  15. this.Prototype.DefineOwnProperty("constructor", new DataDescriptor(this) { Writable = true, Enumerable = false, Configurable = false }, false);
  16. this.Prototype.DefineOwnProperty("prototype", new DataDescriptor(this.Prototype) { Writable = true, Enumerable = false, Configurable = false }, false);
  17. // Array method
  18. this.Prototype.DefineOwnProperty("push", new DataDescriptor(new BuiltInPropertyWrapper(engine, (Action<ArrayInstance, object>)Push, engine.RootFunction)), false);
  19. this.Prototype.DefineOwnProperty("pop", new DataDescriptor(new BuiltInPropertyWrapper(engine, (Func<ArrayInstance, object>)Pop, engine.RootFunction)), false);
  20. }
  21. public override object Call(object thisObject, object[] arguments)
  22. {
  23. return Construct(arguments);
  24. }
  25. public ObjectInstance Construct(object[] arguments)
  26. {
  27. var instance = new ArrayInstance(Prototype);
  28. instance.DefineOwnProperty("length", new AccessorDescriptor(() => instance.Length, x => { }), false);
  29. foreach (var arg in arguments)
  30. {
  31. instance.Push(arg);
  32. }
  33. return instance;
  34. }
  35. private static void Push(ArrayInstance thisObject, object o)
  36. {
  37. thisObject.Push(o);
  38. }
  39. private static object Pop(ArrayInstance thisObject)
  40. {
  41. return thisObject.Pop();
  42. }
  43. }
  44. }