In Javascript, a function starts a new scope, but we have to be careful that the function must be invoked so that the scope is created, is that so? -
in javascript, immerged in idea function creates new scope, think following anonymous function create new scope when being defined , assigned onclick:
<a href="#" id="link1">ha link 1</a> <a href="#" id="link2">ha link 2</a> <a href="#" id="link3">ha link 3</a> <a href="#" id="link4">ha link 4</a> <a href="#" id="link5">ha link 5</a> <script type="text/javascript"> (i = 1; <= 5; i++) { document.getelementbyid('link' + i).onclick = function() { var x = i; alert(x); return false; } } </script> but in fact, anonymous function create new scope, that's right, when being invoked, so? x inside anonymous function not created, no new scope created. when function later invoked, there new scope alright, i in outside scope, , x gets value, , 6 anyways.
the following code invoke function , create new scope , that's why x new local variable x in brand new scope each time, , invocation of function when link clicked on use different x in different scopes.
<a href="#" id="link1">ha link 1</a> <a href="#" id="link2">ha link 2</a> <a href="#" id="link3">ha link 3</a> <a href="#" id="link4">ha link 4</a> <a href="#" id="link5">ha link 5</a> <script type="text/javascript"> (i = 1; <= 5; i++) { (function() { var x = i; document.getelementbyid('link' + i).onclick = function() { alert(x); return false; } })(); // invoking now! } </script> if take away var in front of x, global x , no local variable x created in new scope, , therefore, clicking on links same number, value of global x.
update: question is: have careful when analyze code, function not create scope when merely defined , assigned. has invoked. so?
the scope of function set when function object created, example:
var fn; // augment scope chain: ({foo: "bar"}) { fn = function () { // create function return foo; }; } // restored scope chain fn(); // "bar" in above example, function created inside with block, there current scope being augmented, introduce object foo property scope chain.
in second example, happens same, onclick handler function being created inside auto-invoking anonymous function, has created new lexical scope.
at moment function auto-invoked on each loop iteration, value of i captured scope in x variable, onclick handler function created inside scope, , able resolve it.
Comments
Post a Comment