For tl;dr, When creating click handlers for rows in a table, using a closure makes the function point to the same place in memory, not a different place each time like with the code below.
otherwise:
I'm learning javascript and I think I understand what a closure is and why it's useful. Here's my reasoning; is it correct?
For an HTML table, the code below always shows the last row being clicked, even if I click on the first or second row. My reasoning is the code creates 3 different stack frames, one each for i equaling 0, 1 and 2. Since 2 is the most recent stack frame, the return value of fnPtr points to 2.
var table = document.getElementById("tableid3");
var rows = table.getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++) {
var curRow = table.rows[i];
//get cell data from first col of row
var cell = curRow.getElementsByTagName("td")[0];
var fnPtr = function() {
alert("row " + i + " data="+ cell.innerHTML);
}
curRow.onclick = fnPtr;
}
Now the code below (from a SO question) uses a closure and creates only a single stack frame, the frame for createfunc(). But inside this frame is a local variable tmp, which points to the anonymous function. When createfunc() is called with 0, 1, and 2, the return value points to the same stack frame (the stack frame inside the stack frame of createfunc()) meaning that 3 stack frames are not created. When createfunc() returns each time, the value in the return value slot points to the same place in memory, not a different place each time like with the code above.
function createfunc(i) {
var tmp = function() { console.log("My value: " + i); };
console.log(tmp);
return tmp;
}
for (var i = 0; i < 3; i++) {
funcs[i] = createfunc(i);
}
for (var j = 0; j < 3; j++) {
funcs[j](); // and now let's run each one to see
}
Am I understanding how closures work?