ObjectConstructor.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using Jint.Native.Function;
  2. using Jint.Runtime;
  3. using Jint.Runtime.Descriptors;
  4. using Jint.Runtime.Descriptors.Specialized;
  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, false)
  11. {
  12. _engine = engine;
  13. engine.RootFunction.DefineOwnProperty("hasOwnProperty", new ClrDataDescriptor<ObjectInstance, bool>(engine, HasOwnProperty), false);
  14. engine.RootFunction.DefineOwnProperty("toString", new ClrDataDescriptor<ObjectInstance, string>(engine, ToString), 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, object[] arguments)
  29. {
  30. var propertyName = TypeConverter.ToString(arguments[0]);
  31. var desc = thisObject.GetOwnProperty(propertyName);
  32. return desc != PropertyDescriptor.Undefined;
  33. }
  34. private static string ToString(ObjectInstance thisObject, object[] arguments)
  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. }