I was reading a blog post here about creating a scraper with node.js
and came across an interesting bit of javascript that I can't quite wrap my head around. This is the exact sort of thing I would like to use in my scripts, but as a bit of a newbie I don't want to blindly copy and paste code without knowing exactly what they do first.
In this function:
function main()
{
var a = 1;
var f = function() { console.log(a); }
a = 2;
f();
}
main();
the output is 2
, because var a
is changed before f()
is called.
However, in this function
function main()
{
var a = 1;
var f = ( function(a) { return function() { console.log(a); } } )(a);
a = 2;
f();
}
main();
the output is 1
. There is a fairly detailed explanation of this in the blog post linked above, but I can't for the life of me work out exactly why this works.
The post mentions the scope of var a
being passed into the function - can anyone elaborate on what this means? And why is it necessary to have the final (a)
at the end of the var f
function?