Why does it matter that in Javascript the scope is function level and not block level?
In question
Javascript infamous loop problem?
the accepted answer by Christoph says
JavaScript scopes are functional level, not block level
What if Javascript scopes are blocky then the Infamous Loop problem will still occur? Or will there be another (and easier) way to fix it?
Is this in contrast to other languages, where use {
starts a new scope?
a source to share
I found the answer:
Javascript 1.7 and above supports the bulk level, and Firefox 3.0 and above supports it. (See http://en.wikipedia.org/wiki/Javascript#Versions )
I tried the following code using Firefox 3.5.9:
Note that a keyword is used let
which will create a block level area.
<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="application/javascript;version=1.7"/>
for (i = 1; i <=5; i++) {
let x = i;
document.getElementById('link' + i).onclick = function() { alert(x); return false; }
}
</script>
Of course, a new area is created with a new one x
. The anonymous function that does alert(x)
captures this area (the entire chain of chains) and remembers it, thereby forming a closure. When this anonymous function is called, the scope is, and when it searches x
, of course, x
is in that scope as 1, 2, 3, 4, 5, respectively. Try and change let
to var
and you get the infamous old problem again because no new area is created.
a source to share
If the blocks were creating areas (for closures), then this will work the way people who later post a question to StackOverflow think this might work:
for (var i = 0; i < thing.length; ++i) {
var element = $('#elem' + i); // making this up randomly here
setTimeout(function() { doSomething(element); }, 100);
}
This will work because each iteration of the loop body will (possibly) create a new scope and therefore a new "item". Be that as it may, the fact that a new scope is not created means that every function created as it passes through the loop has the same "element" variable and therefore the code does not work as expected and another question arises. StackOverflow javascript
.
a source to share
Basically, this is a way of saying that the value obtained with the first setting is a "pointer" - a reference to the value of the variable when the method is called. In the second case, the value is a "copy", not a "pointer", so each instance has its own value.
Let's assume I read your question correctly.
a source to share