0

So I'm reading this article about JavaScript Lexical scoping, and the author points out that "JavaScript is not truly static". He then "proves" this by the following example:

var count = 5;

function tellCount() {
    console.log(count);
};
tellCount(); //prints 5
count = 7;
tellCount(); //prints 7;

What am I missing here? He put the count variable in the global namespace as five, calls the method that references the global variable and prints five, then changes the global variable to seven and calls the method again. If I'm not mistaken, changing a global variable and re-calling a method that uses the variable would do this in any statically scoped language.

Does the author truly prove that JavaScript is not truly statically scoped?

Note: I know that eval in JavaScript introduces a form of dynamic scope into JS, but I'm more interested on proving / disproving what this author wrote.

contactmatt
  • 18,116
  • 40
  • 128
  • 186
  • 1
    See: http://stackoverflow.com/questions/958983/are-variables-statically-or-dynamically-scoped-in-javascript – jfriend00 Feb 21 '13 at 05:38
  • I think the author is confused between scope and how values are assigned to variables. The examples don't show changing scope, only that the value of variables in that scope can change, and that variables can be on more than one scope chain. – RobG Feb 21 '13 at 05:50

2 Answers2

1

You are not missing anything and the author is wrong. Lexical scope means that the closure has access to the variables in the defining function, not that thay are magically copied over when the closure is defined.

a sad dude
  • 2,775
  • 17
  • 20
0

I think this is a bad example. Next example of article shows more effective reference mechanism:

var numbers = [1, 2, 3, 4, 5];
for (var i in numbers) {
    var num = numbers[i];
    var anchor = document.createElement('A');
    anchor.setAttribute('href', '#');
    anchor.appendChild(document.createTextNode(num));
    document.body.appendChild(anchor);

    anchor.addEventListener('click', function(event) {
        alert('My number is ' + num);
        event.preventDefault();
    }, false);
}
Damask
  • 1,754
  • 1
  • 13
  • 24