以下是引用片段: <script type="text/javascript"> function sayHello2(name) { var text = 'Hello ' + name; // local variable var sayAlert = function() { alert(text); } return sayAlert; } var sy = sayHello2('never-online'); sy(); </script> |
以下是引用片段: <script type="text/javascript"> function say667() { // Local variable that ends up within closure var num = 666; var sayAlert = function() { alert(num); } num++; return sayAlert; } var sy = say667(); sy(); alert(sy.toString()); </script> |
以下是引用片段: <script type="text/javascript"> function setupSomeGlobals() { // Local variable that ends up within closure var num = 666; // Store some references to functions as global variables gAlertNumber = function() { alert(num); } gIncreaseNumber = function() { num++; } gSetNumber = function(x) { num = x; } } </script> <button onclick="setupSomeGlobals()">生成 - setupSomeGlobals()</button> <button onclick="gAlertNumber()">输出值 - gAlertNumber()</button> <button onclick="gIncreaseNumber()">增加 - gIncreaseNumber()</button> <button onclick="gSetNumber(5)">赋值5 - gSetNumber(5)</button> |
以下是引用片段: <script type="text/javascript"> function buildList(list) { var result = []; for (var i = 0; i < list.length; i++) { var item = 'item' + list[i]; result.push( function() {alert(item + ' ' + list[i])} ); } return result; } function testList() { var fnlist = buildList([1,2,3]); // using j only to help prevent confusion - could use i for (var j = 0; j < fnlist.length; j++) { fnlist[j](); } } testList(); </script> 运行结果: item 3 is undefined item 3 is undefined item 3 is undefined 代码result.push( function() {alert(item + ' ' + list[i])} ), 使result数组添加了三个匿名函数的引用。这句代码也可以写成 var p = function() {alert(item + ' ' + list[i])}; result.push(p); |
以下是引用片段: <script type="text/javascript"> function newClosure(someNum, someRef) { // Local variables that end up within closure var num = someNum; var anArray = [1,2,3]; var ref = someRef; return function(x) { num += x; anArray.push(num); alert('num: ' + num + '/nanArray ' + anArray.toString() + '/nref.someVar ' + ref.someVar); } } var closure1 = newClosure(40, {someVar:' never-online'}) var closure2 = newClosure(99, {someVar:' BlueDestiny'}) closure1(4) closure2(3) </script> |
在这最后一个例子中,展示如何声明两个不同的闭包。