Why does one JavaScript closure work and the other doesn't? - javascript

There are two versions, supposedly when the user click the first link, it will alert "1", and the second link, "2", etc.:
Version 1:
click me
click me
click me
click me
click me
<script type="text/javascript">
for (i = 1; i <= 5; i++) {
document.getElementById('link' + i).onclick = (function() {
return function() {
var n = i;
alert(n);
return false;
}
})();
}
</script>
Version 2:
click me
click me
click me
click me
click me
<script type="text/javascript">
for (i = 1; i <= 5; i++) {
document.getElementById('link' + i).onclick = (function() {
var n = i;
return function() {
alert(n);
return false;
}
})();
}
</script>
Version 1 will not work. Version 2 will. I think I know the reason why, but would like to compare with other people's explanations as to why version 1 doesn't work.

Version 1 does not work because there's a common variable "i" (a global variable in this case, because you forgot var) that is shared by every "click" handler function the loop creates.
In the second version, you create a new lexical scope with the little wrapper function. That gives each "click" handler it's very own private "i".

In the second example you create a var n = i; it makes i value scoped inside the onclick function. While at the first one the onclick function still uses global value of i
I'd suggest this usage instead:
for (i = 1; i <= 5; i++) {
document.getElementById('link' + i).onclick = (function(i) {
return function() {
alert(i);
return false;
}
})(i);
}
In this case you'll get the same behaviour since i will be the local variable for onclick function as it's an argument.

First does not work because: i is the part of each closure. After 5 iterations now i is 6 due to postfix increment operator. Each time when event handler is invoked it gets the value of i from its closure scope that is always 6.
Second part works: because each closure makes a copy of i in n, n is part of each closure.

Related

Implementing loop for var names for clickTags

Need to add for a banner three clickTags which have names like clickTag1, clickTag2,clickTag3. Now the code looks like this:
for(var i = 1; i <= 3; i++) {
document.getElementById('Destination_cta_' + i).addEventListener('click', function() {
window.open(clickTag2, '_blank'); //here I want clickTag look like clickTag + i, but its not working.
})
}
So the question is how to loop var names so I wont need to put it manually, like it is now.
The cleanest way to solve this problem would be to use an Array.
[, clickTag1, clickTag2, clickTag3].forEach(function(e, i) {
document.getElementById('Destination_cta_' + i).addEventListener('click', function() {
window.open(e, '_blank');
})
})
An alternative method: if your clickTags are global variables, you could always access them as global properties of the window object:
for(var i = 1; i <= 3; i++) (function (i) {
document.getElementById('Destination_cta_' + i).addEventListener('click', function() {
window.open(window['clickTag' + i], '_blank')
})
)(i)
The additional wrapping function fixes the closure bug mentioned in the comments above.
You want to use an array for this. An array is an indexed list of values.
var clickTags = ["","www.nba.com","www.nhl.com","www.nfl.com"];
for(var i = 1; i <= 3; i++) {
document.getElementById('Destination_cta_' + i).addEventListener('click', function() {
window.open(clickTags[i], '_blank'); //here I want clickTag look like clickTag + i, but its not working.
})
}
Notice since you are starting your loop at 1 instead of 0, i've added a blank entry for index 0 of the clickTags array.
Why it is not currently working the way you intend :
for (var i = 1; i <= 3; i++) {
// During your first loop there is a local variable `i` whose value is 1
document.getElementById('Destination_cta_' + i)
// Here you pass an anonymous function as the second argument to addEventListener
// This creates a closure, which means the function's context includes variables
// that were in scope when it was created. Right now we have the `for` loop's variable
// `i` in the current scope, so the function keeps a *reference* to that variable.
.addEventListener('click', function() {
// When this get executed in the future, the function has to know about the variable `i`,
// and thankfully there is a reference to it in this function's closure. But remember that
// the for loop executed 3 times, using that same variable. That means that every function
// was created with a closure that is keeping a reference to the same variable, whose final
// value after the loop finished, was 4.
window.alert('clickTag' + i); // Will always alert 'clickTag4' no matter which is clicked
})
}
<div id="Destination_cta_1">1</div>
<div id="Destination_cta_2">2</div>
<div id="Destination_cta_3">3</div>
How to solve this problem ?
Make sure each addEventListener call gets a function with the correct value in a closure of its own. The way to do this is to use an immediately invoked function expression to which you pass in the value you want :
for (var i = 1; i <= 3; i++) {
var element = document.getElementById('Destination_cta_' + i)
element.addEventListener('click', (function(index) {
// This function is now a closure with a reference to index
return function() {
window.alert('clickTag' + index);
}
})(i)) // calling the anonymous function with the current value of `i` binds that value
// to the function's scope
}
<div id="Destination_cta_1">1</div>
<div id="Destination_cta_2">2</div>
<div id="Destination_cta_3">3</div>

Changing Scope from Global to Local Breaking Javascript Program

Thanks to the help of you fine Overflowians, I fixed up my silly little RNG Addition game and got it working. Now, at one user's suggestion, I'm trying to change the scope of the addition game's code from global to local before I code up the next game; I want each game to be completely contained within its own scope, as I understand that learning to not thoughtlessly contaminate the global scope is a good idea. However, I'm a bit stuck on how to achieve that.
Here's the code for the currently functional addition game:
function beginAdditionChallenge() {
var x = Math.ceil(Math.random()*100);
alert(x);
for (var i = 0; i < 3; i++) {
var a = Number(prompt("Provide the first addend.", ""));
var b = Number(prompt("Provide the second addend.", ""));
if (a + b === x) {
alert("Well done!");
break;
}
else if (a + b !== x && i < 2) {
alert("Please try again.");
}
else {
alert("Derp.");
}
}
}
function initChallenge() {
var button = document.getElementById("challengeButton");
button.addEventListener("click", beginAdditionChallenge);
}
window.addEventListener("load", initChallenge);
And here's my attempt to wrap it, which only succeeds in breaking the game, such that the button doesn't even respond:
window.addEventListener("load", function() {
function beginAdditionChallenge() {
var x = Math.ceil(Math.random()*100);
alert(x);
for (var i = 0; i < 3; i++) {
var a = Number(prompt("Provide the first addend.", ""));
var b = Number(prompt("Provide the second addend.", ""));
if (a + b === x) {
alert("Well done!");
break;
}
else if (a + b !== x && i < 2) {
alert("Please try again.");
}
else {
alert("Derp.");
}
}
}
function initChallenge() {
var button = document.getElementById("challengeButton");
button.addEventListener("click", beginAdditionChallenge);
}
window.addEventListener("load", initChallenge);
});
Functional code is available on JSFiddle here.
Note that the onLoad option in JSFiddle does the same as your 2nd snippet. You'll want to choose one of the No wrap options when binding to 'load' yourself.
And, the issue stems from attempting to bind to 'load' within a 'load' handler:
window.addEventListener("load", function() {
// ...
window.addEventListener("load", initChallenge);
});
When the event is already firing and handling the outer binding, it's too late to add more handlers to it. They won't be cycled through and the event shouldn't occur again.
You'll either want to call initChallenge within the outer event binding:
window.addEventListener("load", function() {
// ...
initChallenge();
});
Or, you can use an IIFE with the inner binding:
(function () {
// ...
window.addEventListener("load", initChallenge);
})();

java script last iteration set the value for all iterations

var myElements = document.getElementsByName('bb1');
for (var i = 0; i < myElements.length; i++) {
var curValue = myElements[i].getAttribute('innerId')
myElements[i].addEventListener('mouseover', function () {
alert('Hello i am : ' + curValue);
}, false);
}
when mouse over, every element, instead of showing a different value for curValue, a constant value (the last iteration value) is displayed.
what am i doing wrong here?
There is no different scope inside blocks like for in JavaScript, so when your mouseover event is triggered, it will alert the current variable value which was set in the last iteration.
You can just use this inside your callback function to get the attribute of the object which the event was triggered.
var myElements = document.getElementsByName('bb1');
for (var i = 0; i < myElements.length; i++) {
myElements[i].addEventListener('mouseover', function () {
alert('Hello i am : ' + this.getAttribute('innerId'));
}, false);
}
The general issue here is the closure in Javascript. This happens when using variable (in this case curValue) not defined within the callback function.
I recommend reading answers about JS closures here.

Variable scoping and event handler

Please see the jsfiddle:
http://jsfiddle.net/LsNCa/2/
function MyFunc() {
for (var i = 0; i < 2; i++) { // i= 0, 1
var myDiv = $('<div>');
myDiv.click(function(e) {
alert(i); // both the two divs alert "2", not 0 and 1 as I expected
});
$('body').append(myDiv);
}
}
var myFunc = new MyFunc();
I want the divs to alert "0" and "1" respectively when I click them, but both of them alert "2".
When I click the divs and the event is triggered, how and where do the handler find the value of the variable i?
I'm aware that adding a closure achieves my goal. But why?
function MyFunc() {
for (var i = 0; i < 2; i++) { // i= 0, 1
(function(j) {
var myDiv = $('<div>');
myDiv.click(function(e) {
alert(j);
});
$('body').append(myDiv);
})(i);
}
}
var myFunc = new MyFunc();
The code above is how you get it work correctly. Without an closure, you always the the last value of i. What we do is to post i into the closure and let the runtime "remember" the value of that very moment.
You need a closure because all your event handler functions are referencing the same variable i. The for loop updates this, and when the loop is done the variable contains 2. Then when someone clicks on one of the DIVs, it accesses that variable.
To solve this, each event handler needs to be a closure with its own variable i that contains a snapshot of the value at the time the closure was created.
I suggest that you read this article
JavaScript hoists declarations. This means that both var statements
and function declarations will be moved to the top of their enclosing
scope.
As #Barmar said in his answer above, the variable i is being referenced by both the event handlers.
You should avoid declaring functions inside loops. Below there is some code that does what you need.
I assume that you're using jQuery.
function MyFunc() {
for (var i = 0; i < 2; i++) { // i= 0, 1
var myDiv = $('<div>');
$('body').append(myDiv);
}
$('div').on('click', function() {
alert($(this).index());
});
}
var myFunc = new MyFunc();
The "alert()" call happens after the for-loop completed, which means that the value of "i" will be the last value for anything after that. In order to capture individual values of "i", you must create a closure for each value by creating a new function:
function MyFunc() {
function alertFn(val) {
return function () {
alert(val);
};
}
for (var i = 0; i < 2; i++) {
var myDiv = $('<div>');
myDiv.click(alertFn(i));
$('body').append(myDiv);
}
}
var myFunc = new MyFunc();
The closure captures the value of "i" at the time it was passed into the function, allowing alert() to show the value you expect.

variable closure using jQuery object notation

I have the following:
for (var i = 0; i <= 10; i += 1) {
var $page_button = $('<a>', {
html : i,
click : function () {
var index = i;
console.log(index);
return false;
}
});
$page_button.appendTo($wrapper);
}
I thought that var index would be defined separately for each iteration of the loop because it is enclosed within a function. In this case the value of index that is printed is always 10.
The link text is the correct value of i, because this is written to the DOM and is then immutable .
Why is this, and what should I change to fix my problem?
I know this is similar to lots of other questions but the behaviour of using this notation is causing a different result. I am using jQuery 1.7.2 (Can't use any newer unfortunately.)
You need to enclose that in a closure to solve the problem..
var $page_button = $('<a>', {
html : i,
click : (function (num) {
return function(){
var index = num;
console.log(index);
return false;
}
})(i)
});
A reference to i is closed up as part of the anonymous function. Note: not to its value, but a reference to i itself. When the function is run, the value is evaluated. Because the function runs after the loop has ended, the value will always be the last value of i. To pass just the value around, you do something like this:
click : (function (index) {
return function () {
console.log(index);
return false;
};
})(i)
You create an anonymous function which you execute immediately, which takes a value as argument and returns your actual function.
The variable index is defined separately for each execution of the function, but you copy the value from the variable i inside the function, so you will use the value of i as it is when the function runs, not when the function is created.
You need a function that is executed inside the loop to capture the value of the variable:
for (var i = 0; i <= 10; i += 1) {
(function(){
var index = i;
var $page_button = $('<a>', {
html : i,
click : function () {
console.log(index);
return false;
}
});
})();
$page_button.appendTo($wrapper);
}
Every handler is sharing the same i variable. Each one needs its own variable scope in order to reference a unique index.
for (var i = 0; i <= 10; i += 1) {
var $page_button = $('<a>', {
html : i,
click : makeHandler(i) // invoke makeHandler, which returns a function
});
$page_button.appendTo($wrapper);
}
function makeHandler(index) {
return function () {
console.log(index);
return false;
};
}
Here I made a makeHandler function that accepts the index argument, and returns a function that is used as the handler.
Because a function invocation sets up a new variable scope, and because a function is created and returned inside the makeHandler, each handler returned will reference its own scoped index number.

Categories

Resources