FunctionPrototype.cs 2.4 KB

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