Inspired from this Stackoverflow question, the answer by João Silva: setTimeout with arguments
I was wondering if someone could explain to me exactly how this code snippet differs from the latter:
// Parameter to use
var bar = 'bar';
// Go
setTimeout(
(function(arg1){
return function () {
console.log(arg1); //ya arg1 has the value: 'bar'!
}
}(bar)), 2000);
I was expecting the parentheses to be slightly different and I understand that this is a Immediately-Invoked Function Expression (coined by Ben Alman I believe) combined with a closure but I don't exactly understand how this code executes.
I was picturing a self invoked anonymous function invoked by a closure, which I understand how it works, at least mildly.
// Parameter to use
var bar = 'bar';
// Go
setTimeout(
(function(arg1){
return function () {
console.log(arg1); //ya arg1 has the value: 'bar'!
}
})(bar), 2000);
So both work, and it is only one parentheses difference between the two code snippets, and again I am not a javascript expert but I intuitively feel both of these javascript snippets are extremely cross browser compatible. But what really is the different between the two?