I am a C++ ( Qt ) developer and know JS a bit. I am not able to understand a part of below code. Can you please help me with this?
function augment(withFn) {
var name, fn;
for (name in window) {
fn = window[name];
if (typeof fn === 'function') {
// **Not able to understand below code.**
window[name] = (function(name, fn) {
var args = arguments;
return function() {
withFn.apply(this, args);
fn.apply(this, arguments);
}
})(name, fn);
// **In above code I understood everything else except this last line.
// Why whole function is in circular bracket? Why it ends with (name, fn);
// What is the meaning of this?
}
}
}
augment(function(name, fn) {
console.log("calling " + name);
});
The self executed anonymous function is a common way to solve an issue with closures in a loops.
So it’s practically an anonymous function that is declared and executed immediately with passed parameters.
Actually
nameparameter is useless there, since it’s not used, but if you didn’t do the trick – then only the lastfnparameter would be passed as a reference.The demonstration of the issue: http://jsfiddle.net/zerkms/nfjtn/
The solution (using the self-executing anonymous function): http://jsfiddle.net/zerkms/nfjtn/1/