StringConstructor.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using Jint.Native.Function;
  2. using Jint.Native.Object;
  3. using Jint.Runtime;
  4. using Jint.Runtime.Descriptors;
  5. using Jint.Runtime.Interop;
  6. namespace Jint.Native.String
  7. {
  8. public sealed class StringConstructor : FunctionInstance, IConstructor
  9. {
  10. public StringConstructor(Engine engine)
  11. : base(engine, null, null, false)
  12. {
  13. }
  14. public static StringConstructor CreateStringConstructor(Engine engine)
  15. {
  16. var obj = new StringConstructor(engine);
  17. obj.Extensible = true;
  18. // The value of the [[Prototype]] internal property of the String constructor is the Function prototype object
  19. obj.Prototype = engine.Function.PrototypeObject;
  20. obj.PrototypeObject = StringPrototype.CreatePrototypeObject(engine, obj);
  21. obj.SetOwnProperty("length", new PropertyDescriptor(1, PropertyFlag.AllForbidden));
  22. // The initial value of String.prototype is the String prototype object
  23. obj.SetOwnProperty("prototype", new PropertyDescriptor(obj.PrototypeObject, PropertyFlag.AllForbidden));
  24. return obj;
  25. }
  26. public void Configure()
  27. {
  28. SetOwnProperty("fromCharCode", new PropertyDescriptor(new ClrFunctionInstance(Engine, FromCharCode, 1), PropertyFlag.NonEnumerable));
  29. }
  30. private static JsValue FromCharCode(JsValue thisObj, JsValue[] arguments)
  31. {
  32. var chars = new char[arguments.Length];
  33. for (var i = 0; i < chars.Length; i++ )
  34. {
  35. chars[i] = (char)TypeConverter.ToUint16(arguments[i]);
  36. }
  37. return new System.String(chars);
  38. }
  39. public override JsValue Call(JsValue thisObject, JsValue[] arguments)
  40. {
  41. if (arguments.Length == 0)
  42. {
  43. return "";
  44. }
  45. return TypeConverter.ToString(arguments[0]);
  46. }
  47. /// <summary>
  48. /// http://www.ecma-international.org/ecma-262/5.1/#sec-15.7.2.1
  49. /// </summary>
  50. /// <param name="arguments"></param>
  51. /// <returns></returns>
  52. public ObjectInstance Construct(JsValue[] arguments)
  53. {
  54. return Construct(arguments.Length > 0 ? TypeConverter.ToString(arguments[0]) : "");
  55. }
  56. public StringPrototype PrototypeObject { get; private set; }
  57. public StringInstance Construct(string value)
  58. {
  59. return Construct(JsString.Create(value));
  60. }
  61. public StringInstance Construct(JsString value)
  62. {
  63. var instance = new StringInstance(Engine)
  64. {
  65. Prototype = PrototypeObject,
  66. PrimitiveValue = value,
  67. Extensible = true,
  68. _length = new PropertyDescriptor(value.Length, PropertyFlag.AllForbidden)
  69. };
  70. return instance;
  71. }
  72. }
  73. }