ObjectConstructor.cs 2.1 KB

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