From 0ce304cca80d1de4eed07f1efbb69b9693b6df2b Mon Sep 17 00:00:00 2001 From: Garrett Johnson <=> Date: Sat, 4 Jun 2011 02:38:09 -0400 Subject: [PATCH 1/2] added closure examples sans-jquery --- content/javascript-101/closures.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/content/javascript-101/closures.md b/content/javascript-101/closures.md index 9e70de71..db28e57b 100644 --- a/content/javascript-101/closures.md +++ b/content/javascript-101/closures.md @@ -19,11 +19,11 @@ function is defined, resulting in all clicks alerting 5. How to lock in the value of i? /* this won't behave as we want it to; */ - /* every click will alert 5 */ + /* every 100 milliseconds, 5 will alert */ for (var i=0; i<5; i++) { - $('
click me
').appendTo('body').click(function() { - alert(i); - }); + setTimeout(function() { + alert(i); + }, i*100); } @@ -36,7 +36,7 @@ Locking in the value of i with a closure }; for (var i=0; i<5; i++) { - $('click me
').appendTo('body').click(createFunction(i)); + setTimeout( createFunction(i), i*100 ); } From 4c2d13a91883a1651d0d7d34c29290f93ad3974f Mon Sep 17 00:00:00 2001 From: Garrett Johnson <=> Date: Sat, 4 Jun 2011 11:39:00 -0400 Subject: [PATCH 2/2] added new content and fixed code examples not being styled correctly --- content/javascript-101/closures.md | 96 +++++++++++++++--------------- 1 file changed, 49 insertions(+), 47 deletions(-) diff --git a/content/javascript-101/closures.md b/content/javascript-101/closures.md index db28e57b..6f8efa7e 100644 --- a/content/javascript-101/closures.md +++ b/content/javascript-101/closures.md @@ -13,23 +13,25 @@ example. In the functions section, we saw how functions have access to changing variable values. The same sort of behavior exists with functions defined within loops -- the function "sees" the change in the variable's value even after the -function is defined, resulting in all clicks alerting 5. +function is defined, resulting in each function referencing the last value stored +in the variable.