FunctionPrototype.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. using System.Collections.Generic;
  3. using Jint.Native.Object;
  4. using Jint.Runtime;
  5. using Jint.Runtime.Interop;
  6. namespace Jint.Native.Function
  7. {
  8. /// <summary>
  9. /// http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.4
  10. /// </summary>
  11. public sealed class FunctionPrototype : FunctionInstance
  12. {
  13. private FunctionPrototype(Engine engine):base(engine, null, null, false)
  14. {
  15. }
  16. public static FunctionPrototype CreatePrototypeObject(Engine engine)
  17. {
  18. var obj = new FunctionPrototype(engine);
  19. // The value of the [[Prototype]] internal property of the Function prototype object is the standard built-in Object prototype object
  20. obj.Prototype = engine.Object.PrototypeObject;
  21. obj.FastAddProperty("length", 0, false, false, false);
  22. return obj;
  23. }
  24. public void Configure()
  25. {
  26. FastAddProperty("apply", new ClrFunctionInstance<object, object>(Engine, Apply), false, false, false);
  27. }
  28. public object Apply(object thisObject, object[] arguments)
  29. {
  30. if (arguments.Length != 2)
  31. {
  32. throw new ArgumentException("Apply has to be called with two arguments.");
  33. }
  34. var func = thisObject as ICallable;
  35. var thisArg = arguments[0];
  36. var argArray = arguments[1];
  37. if (func == null)
  38. {
  39. throw new JavaScriptException(Engine.TypeError);
  40. }
  41. if (argArray == Null.Instance || argArray == Undefined.Instance)
  42. {
  43. return func.Call(thisArg, Arguments.Empty);
  44. }
  45. var argArrayObj = argArray as ObjectInstance;
  46. if (argArrayObj == null)
  47. {
  48. throw new JavaScriptException(Engine.TypeError);
  49. }
  50. var len = argArrayObj.Get("length");
  51. var n = TypeConverter.ToUint32(len);
  52. var argList = new List<object>();
  53. for (var index = 0; index < n; index++)
  54. {
  55. var indexName = index.ToString();
  56. var nextArg = argArrayObj.Get(indexName);
  57. argList.Add(nextArg);
  58. }
  59. return func.Call(thisArg, argList.ToArray());
  60. }
  61. public override object Call(object thisObject, object[] arguments)
  62. {
  63. return Undefined.Instance;
  64. }
  65. }
  66. }