StringConstructor.cs 2.6 KB

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