The following does not do what you would expect, when clicking li elements in the list it always references the last person in the array.
var people = ["Foo", "bar", "baz"];
var list = document.getElementById("people-list");
for (var i = 0; i < people.length; i++) {
var person = people[i];
var element = document.createElement("li");
element.innerText = person;
element.addEventListener("click", function() {
alert("You clicked on " + person + ", at index " + i);
});
}
Example 2
var a = 42;
var b = 57;
function example2() {
var a = b = 10;
}
//a = 42, b = 57
example2();
//a = 42, b = 10;
//This is now what you would expect, but how the javascript run-time sees this is;
function example2_clear() {
var a = 10;
b = 10;
}
// So the run time is actually creating a new variable scoped to the function called a.
// But for b this is referencing the b in the global scope.
// This is an example of why the global scope is bad.
Example 3
function example3_otherFunction() {
for (i = 0; i < 5; i++) {
console.log(i + " * 30 = " + (i * 30));
}
}
function example3() {
i = 1;
j = 1;
example3_otherFunction();
console.log("1 + 1 = " + (i + j));
}
example3();
console.log(i);
console.log(window.i);// global to other files
//:result
/*
0 * 30 = 0
1 * 30 =30
2 * 30 = 60
3 * 30 = 90
4 * 30 = 120
1 + 1 = 6
*/
// The problem here is that both i's are attached to the global scope by not using "var" and
//example3_otherFunction is called and changes it to 5 after it has finished. Then 5 + 1 is equal to
// 6. But not the 1+1 that was expected. In the case of running in chrome the global scope is `window`
// The question to always ask yourself is where do your variables live in memory which scope
// within the javascript virtual machine?
Scopes and Closures
Example 1
The following does not do what you would expect, when clicking li elements in the list it always references the last person in the array.
Example 2
Example 3
What is "this"?
Prototypes