ObjectConstructor.cs 2.1 KB

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