Summary of “Events in JavaScript”, part 2
Scope
A scope determines where variables can be accessed by name. Each function has a local scope for its parameters and variables declared with var.
The scope is limited by the function, which means that you cannot directly access local variables and function parameters by name from outside of this scope.
Local variables in these examples are declared inside a function and belong to its scope. This scope is called local.
Global variables are variables that are declared at the level of the entire program. Functions can access them unless a closer scope declares a variable with the same name. The scope in which they are declared is called global.
If a non-local variable is accessed inside the function, JavaScript will look for the name in enclosing scopes, moving progressively up from one level to the next until it finds the desired variable. If the variable cannot be found either inside the function or outside of it, JavaScript throws an error.
Code in an enclosing scope can reassign a variable that the function uses. The function reads its current value when it runs.
var food = 'pasta';
var eatDinner = function () {
console.log('I ate ' + food);
};
eatDinner();
// Outputs: I ate pasta.
// We assign a new value to the variable food.
food = 'celery';
eatDinner();
// Outputs: I ate celery.
Reassigning outer variables that are used by the function is not a best practice. When you do this, it can lead to unexpected consequences and errors in the code. You need to use this technique carefully.
In these examples, variables declared with var belong to the surrounding function scope, or to the global scope at the top level. Declaring a var variable in a loop does not create a separate scope for it on each iteration.
Closures
A closure is a function that remembers its surroundings. This is the function + access to the variables outside its local scope that it uses.
Closures allow us to keep access to variables from an enclosing scope as well as to use the function itself later.
var collectContainer = function (food) {
return function () {
console.log('I ate ' + food);
};
};
var schoolkid = collectContainer('pasta');
schoolkid();
// Outputs: I ate pasta.
Closures and Asynchrony
Click handlers run later, after the loop registering them has finished, so a shared loop counter may have changed. In the gallery, we call a helper function for each thumbnail to create a separate scope with its own thumbnail and photo parameters. Each handler keeps access to the parameters from that call, so it uses the matching photo path instead of the shared counter.
var thumbnails = document.querySelectorAll('.gallery__photo-preview');
var fullPhoto = document.querySelector('.full-photo');
var addThumbnailClickHandler = function (thumbnail, photo) {
thumbnail.addEventListener('click', function () {
fullPhoto.src = photo;
});
};
for (var i = 0; i < thumbnails.length; i++) {
addThumbnailClickHandler(thumbnails[i], photos[i]);
}
Continue