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 name parameter is useless there, since it's not used, but if you didn't do the trick - then only the last fn parameter 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/
The expression in parentheses (what you call "circular brackets") is an anonymous function. (name, fn) at the end of it means that the function should be called with those arguments, and the return value is assigned to window[name]. It's approximately equivalent to:
tempfn = function(name, fn) { /* body */ };
window[name] = tempfn(name, fn);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With