ObjectConstructor.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using Jint.Native.Function;
  3. using Jint.Runtime;
  4. using Jint.Runtime.Descriptors;
  5. using Jint.Runtime.Interop;
  6. namespace Jint.Native.Object
  7. {
  8. public class ObjectConstructor : FunctionInstance
  9. {
  10. private readonly Engine _engine;
  11. public ObjectConstructor(Engine engine) : base(engine, engine.RootFunction, null, null)
  12. {
  13. _engine = engine;
  14. engine.RootFunction.DefineOwnProperty("hasOwnProperty", new DataDescriptor(new BuiltInPropertyWrapper(engine, (Func<ObjectInstance, string, bool>)HasOwnProperty, engine.RootFunction)), false);
  15. engine.RootFunction.DefineOwnProperty("toString", new DataDescriptor(new BuiltInPropertyWrapper(engine, (Func<ObjectInstance, string>)ToString, engine.RootFunction)), false);
  16. }
  17. public override dynamic Call(object thisObject, dynamic[] arguments)
  18. {
  19. return Undefined.Instance;
  20. }
  21. public ObjectInstance Construct(dynamic[] arguments)
  22. {
  23. var instance = new ObjectInstance(this.Prototype);
  24. // the constructor is the function constructor of an object
  25. instance.DefineOwnProperty("constructor", new DataDescriptor(this) { Writable = true, Enumerable = false, Configurable = false }, false);
  26. instance.DefineOwnProperty("prototype", new DataDescriptor(this.Prototype) { Writable = true, Enumerable = false, Configurable = false }, false);
  27. return instance;
  28. }
  29. private static bool HasOwnProperty(ObjectInstance thisObject, string propertyName)
  30. {
  31. var desc = thisObject.GetOwnProperty(propertyName);
  32. return desc != Undefined.Instance;
  33. }
  34. private static string ToString(ObjectInstance thisObject)
  35. {
  36. if (thisObject == null || thisObject == Undefined.Instance)
  37. {
  38. return "[object Undefined]";
  39. }
  40. if (thisObject == Null.Instance)
  41. {
  42. return "[object Null]";
  43. }
  44. return string.Format("[object {0}]", thisObject.Class);
  45. }
  46. }
  47. }