binding - javascript closure and scope chain example -
can explain me (clearly , concisely) why code works way does? come typed background in java (6 , 7) closures don't exist , not function way in javascript. think concepts related question are: closures , scope chain.
here's example:
var myfuncs = function() { var funcs = [] var i; (i = 0; < 10; i++) { funcs[i] = function() { console.log(i); } } return funcs; } var allfuncs = myfuncs(); allfuncs.foreach(function(fn) { fn(); });
the above example logs 9 (10 times), expectation , own intuition thinking log 0-9.
why work way in javascript? closures powerful, i'm trying grasp concept once , good! modified example produces right output, why?
var myfuncs = function() { var funcs = [] var i; (i = 0; < 10; i++) { funcs[i] = (function(index) { console.log(index); })(i); } return funcs; } var allfuncs = myfuncs(); allfuncs.foreach(function(fn) { fn(); });
closures aren't unique javascript, want see why powerful in context of when javascript actaully written interface browser/dom.
does have good, practical examples of how can apply closure technique when interfacing browser/dom?
thanks.
in examples have, simple.
in first example, there 1 variable i
, references single value. so.. prints number 9
ten times. each function captured shared value of i
changes.
in second example using closure. each function has private variable called index
receives -- , here important part -- copy of value i
.
so, 0
through 9
because there ten functions, each 1 private index
variable , each of index
variables snapshot of i
as existed @ time.
this, longer form of closure, may help:
function myfactory(index) { return function() { console.log(index); } } var myfuncs = function() { var funcs = [] var i; (i = 0; < 10; i++) { funcs[i] = myfactory(i); } return funcs; } var allfuncs = myfuncs(); allfuncs.foreach(function(fn) { fn(); });
Comments
Post a Comment