closure_binding.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. WScript.Echo("Scenario: Multiple closures, with variables that are modified in the parent function");
  6. function write(x) { WScript.Echo(x + ""); }
  7. function f()
  8. {
  9. var y = "before modification";
  10. var ret1 = function()
  11. {
  12. WScript.Echo("1st function");
  13. WScript.Echo(y);
  14. }
  15. y = "after modification";
  16. var ret2 = function()
  17. {
  18. WScript.Echo("2nd function");
  19. WScript.Echo(y);
  20. }
  21. return [ret1,ret2];
  22. }
  23. (function() {
  24. function f() {
  25. write('In f');
  26. }
  27. function g() {
  28. write('In g');
  29. }
  30. var savef = f;
  31. f(f = g);
  32. f = savef;
  33. function foo() {
  34. write(typeof f);
  35. write(typeof g);
  36. }
  37. })();
  38. function g(funcs)
  39. {
  40. funcs[1]();
  41. funcs[0]();
  42. }
  43. var clo = f();
  44. g(clo);
  45. g(clo);
  46. // Side-effect through a closure without eval.
  47. (function(){
  48. var f = function() { a = 2; return 1; }
  49. var a = 1;
  50. WScript.Echo(a + (f() + a));
  51. })();
  52. // Side-effect through a closure with eval.
  53. (function(){
  54. var f = function() { a = 2; return 1; }
  55. var a = 1;
  56. WScript.Echo(a + (f() + a));
  57. eval("");
  58. })();
  59. // Side-effect through a closure inside eval.
  60. (function(){
  61. var f = function() { a = 2; return 1; }
  62. var a = 1;
  63. eval('WScript.Echo(a + (f() + a));');
  64. })();
  65. // No side-effect in nested function.
  66. (function(){
  67. var f = function() { return 1; }
  68. var a = 1;
  69. WScript.Echo(a + (f() + a));
  70. })();