The following snippet is from "Example 5" from this thread on JS and closure. Alternatively, this other thread sort of gets at what I'm curious about.
function buildList(list) {
var result = [];
for (var i = 0; i < list.length; i++) {
var item = 'item' + i;
result.push( function() {alert(item + ' ' + list[i])} );
}
return result;
}
function testList() {
var fnlist = buildList([1,2,3]);
for (var j = 0; j < fnlist.length; j++) {
fnlist[j]();
}
}
The thread this snippet is from says the output is: "item3 undefined"x3. I understand why "item3" is printed all three times, but I don't understand why list[i]
is undefined.
My Question: since list is a parameter of buildList, does that mean it's not a part of the closure of the anonymous function within result.push? If there were a variable within buildList (otherList) which was set to list (and the anonymous function used otherList[i]), would otherList[i] be in the closure? (Therefore instead of "item3 undefined"x3, the output would be "item3 3"x3).
I want to make my component more reusable. In the component I'm binding two values with ngModel: elem.key and elem.value. The problem is that wherever I want to use this component, the element has to ...
I want to make my component more reusable. In the component I'm binding two values with ngModel: elem.key and elem.value. The problem is that wherever I want to use this component, the element has to ...
So im trying to get a div with an iframe in it to reload every 20 sec, i have searched a bit on it, got a code to work on local, but when i upload it to the internet, it wont work, WHY ?. Are there ...
So im trying to get a div with an iframe in it to reload every 20 sec, i have searched a bit on it, got a code to work on local, but when i upload it to the internet, it wont work, WHY ?. Are there ...
I have an array of prime numbers: const primes = [3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97] I want to find the first number in this list that is <= the number given. ...
I have an array of prime numbers: const primes = [3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97] I want to find the first number in this list that is <= the number given. ...
Deep within my promise stack, I make this call: function isNameAvailable(name) { return registry.getName(name) .then(function(result) { return result ? false : true; })...
Deep within my promise stack, I make this call: function isNameAvailable(name) { return registry.getName(name) .then(function(result) { return result ? false : true; })...