In some Javascript code which uses immediate function, it has argument window
or document
like the following:
(function (window, document) {
...
})(window, document);
However, window
and document
are global objects and can be directly accessed as follow:
(function () {
var userAgent = window.navigator.userAgent;
...
var el = document.getElementById(...)
...
})();
What are the differences between the above two codes. Which is better way and why?
Two reasons I can think of:
1) Local variables are the first in the scope chain, so their access is faster than globals (with faster I mean insignificantly faster).
2) Inside the function, window
and document
are local variables, so their names can be minimified:
(function (w, d) {
//var userAgent = w.navigator.userAgent;
)(window, document);
What are the differences between the above two codes. Which is better way and why?
In all practicality and usage in browsers only, there's no appreciable difference.
That said, there's a very slight performance increase that comes from referencing local variables instead of globals.
Also, it allows the flexibility of swapping out the real window
by a mock version; this could be useful during testing and in certain environments where some of the objects are not available and must be replaced.
Btw, there's another kind of argument you could pass, which is undefined
; it goes like this:
(function(undefined) {
// your code
}());
You don't actually pass anything to the outer function and by doing so you make sure that undefined
has not been tampered with; pedantic people like myself would just void 0
for that purpose though :)
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