ArrayConstructor.cs 2.0 KB

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