javascript - 闭包

xiaoxiao2021-02-28  80

1、(http://www.jb51.net/article/83524.htm <html> <body> <p id="demo"></p> <script Language="JavaScript"> function createFunctions(){ var result = new Array(); document.writeln("a"); for (var i = 0; i < 10; i++){ document.writeln("p"); result[i] = function(){ document.writeln("b"); return i; }; } document.writeln("c "+i+" f"); return result; } var funcs = createFunctions(); document.writeln("***"); for (var i=0; i < funcs.length; i++){ document.writeln(funcs[i]()); } </script> </body>

运行结果:

a p p p p p p p p p p c 10 f *** b 10 b 10 b 10 b 10 b 10 b 10 b 10 b 10 b 10 b 10

2、

<html> <body> <pre> <script Language="JavaScript"> function f(x) { var a = 0; a++; document.writeln(a); function inner() { return a + x; } return inner; } var test = f(1); document.writeln(test()); document.writeln(test()); document.writeln(test()); document.writeln("***********"); function a(x) { var i = 0; function b() { i++; return i + x; } return b; } var c = a(1); document.writeln(c()); document.writeln(c()); document.writeln(c()); </script> </pre> </body> </html> 运行结果:

1 2 2 2 *********** 2 3 4

转载请注明原文地址: https://www.6miu.com/read-67162.html

最新回复(0)