Created
April 11, 2014 02:49
-
-
Save ThomasBurleson/10438374 to your computer and use it in GitHub Desktop.
JavaScript - Qualification Test (Senior) > Closures
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function init(list) | |
{ | |
var result = [ ]; | |
for (var i=0; i<list.length; i++) | |
{ | |
var item = 'item' + list[i]; | |
result.push( function() { | |
console.log( item + ' ' + list[i]); | |
}); | |
} | |
return result; | |
} | |
function foo() | |
{ | |
var list = init([1,2,3]); | |
for ( var j=0; j<list.length; j++) | |
{ | |
list[j](); | |
} | |
} | |
foo(); | |
// Code goes here
function init(list)
{
var result = [ ];
for (var i=0; i<list.length; i++)
{
var item = 'item' + list[i];
result.push( makeLogger(i, item) );
}
return result;
// Capture the parameters for future logging
function makeLogger(i, item)
{
return function() {
console.log( item + ' ' + list[i]);
};
}
}
function foo()
{
var list = init([1,2,3]);
for ( var j=0; j<list.length; j++)
{
list[j]();
}
}
foo();
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Question: What does foo() print to the console?
Question: How would you fix it to log
item1 1
item2 2
item3 3