FunctionInstance.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using Jint.Native.Object;
  2. using Jint.Runtime;
  3. using Jint.Runtime.Environments;
  4. namespace Jint.Native.Function
  5. {
  6. public abstract class FunctionInstance : ObjectInstance, ICallable
  7. {
  8. private readonly Engine _engine;
  9. protected FunctionInstance(Engine engine, string[] parameters, LexicalEnvironment scope, bool strict) : base(engine)
  10. {
  11. _engine = engine;
  12. FormalParameters = parameters;
  13. Scope = scope;
  14. Strict = strict;
  15. }
  16. /// <summary>
  17. /// Executed when a function object is used as a function
  18. /// </summary>
  19. /// <param name="thisObject"></param>
  20. /// <param name="arguments"></param>
  21. /// <returns></returns>
  22. public abstract JsValue Call(JsValue thisObject, JsValue[] arguments);
  23. public LexicalEnvironment Scope { get; private set; }
  24. public string[] FormalParameters { get; private set; }
  25. public bool Strict { get; private set; }
  26. public virtual bool HasInstance(JsValue v)
  27. {
  28. var vObj = v.TryCast<ObjectInstance>();
  29. if (vObj == null)
  30. {
  31. return false;
  32. }
  33. var po = Get("prototype");
  34. if (!po.IsObject())
  35. {
  36. throw new JavaScriptException(_engine.TypeError, string.Format("Function has non-object prototype '{0}' in instanceof check", TypeConverter.ToString(po)));
  37. }
  38. var o = po.AsObject();
  39. if (o == null)
  40. {
  41. throw new JavaScriptException(_engine.TypeError);
  42. }
  43. while (true)
  44. {
  45. vObj = vObj.Prototype;
  46. if (vObj == null)
  47. {
  48. return false;
  49. }
  50. if (vObj == o)
  51. {
  52. return true;
  53. }
  54. }
  55. }
  56. public override string Class
  57. {
  58. get
  59. {
  60. return "Function";
  61. }
  62. }
  63. /// <summary>
  64. /// http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.5.4
  65. /// </summary>
  66. /// <param name="propertyName"></param>
  67. /// <returns></returns>
  68. public override JsValue Get(string propertyName)
  69. {
  70. var v = base.Get(propertyName);
  71. var f = v.As<FunctionInstance>();
  72. if (propertyName == "caller" && f != null && f.Strict)
  73. {
  74. throw new JavaScriptException(_engine.TypeError);
  75. }
  76. return v;
  77. }
  78. }
  79. }