Javascript Scope: code block vs a code block with a self executing function cacoon -


i'm trying wrap head around scope issue. take 2 examples:

a)

var sels = ['.a', '.b', '.c']; while ( (var sel = fieldsets.shift()) !== undefined ) {      (function(sel) {         $(sel).click(function() {             console.log(sel);         });     })(sel); } 

in example, when 1 of referenced elements clicked, output .a, .b, or .c.

b)

var sels = ['.a', '.b', '.c']; while ( (var sel = fieldsets.shift()) !== undefined ) {      $(sel).click(function() {         console.log(sel);     }); } 

in example, click result undefined.

i'm misunderstanding how scope applied in these 2 examples, because see it, when .click called in either case, sel no longer exists @ all.

what difference in way scope applied between these 2 cases?

the key in statement of yours:

... because see it, when .click called in either case, sel no longer exists @ all.

in language c, true. not javascript! when function instantiated (as done in both of examples create event handlers), "captures" enclosing context. when function executed, context remains available, unlike in stack-based language. (the topic of "closures" we're talking about, , can find more lucid explanations elsewhere type in here in brief answer.)

the key difference first example introduces new layer. in example, each instantiated event handler gets own private "sel" variable, being parameter anonymous wrapper function. outer "sel" made inaccessible because names match.

in second example, because event handlers share access same unique variable "sel", see same thing when they're called: value of "sel" @ end of loop. value undefined because that's when loop stops.


Comments

Popular posts from this blog

java - Jmockit String final length method mocking Issue -

asp.net - Razor Page Hosted on IIS 6 Fails Every Morning -

c++ - wxwidget compiling on windows command prompt -