for (var i=0, link; i<5; i++) {
link = document.createElement("a");
link.innerHTML = "Link " + i;
link.onclick = function (num) {
return function () {
alert(num);
};
}(i);
document.body.appendChild(link);
}
Since the nested function is a closure it has a reference to the num
argument ,the num
argument at the end of the loop is 4 .Now when the first element gets clicked why does it alerts 1 ?It should alert 4 .What is the reason for alerting 1 ?Dont it reference to num
argument?or what is the reason?
But here the case is different:
function foo(x) {
var tmp = 3;
return function (y) {
alert(x + y + (++tmp));
}
}
var bar = foo(2); // bar is now a closure.
bar(10);
The above function will alert 16, because bar can still refer to arg x
and tmp
, even though it is no longer directly inside the scope.
This proves that the closure also have reference to arguments value than why the above code not alerting 4 everytime?