I'm trying to understand the difference between:
(function(document) {
//do stuff with document
})(document);
and
(function() {
//do stuff with document
})();
I'm unsure why the convention appears to be to pass document
and sometimes window
too to the function? Is it to do with scope?
This becomes especially handy if you use a compressor/uglifier like UglifyJS. It then replaces document
with say a
, making your code shorter.
So something like
(function(document, window){
var body = document.body;
var foo = document.querySelector('foo');
var bar = document.querySelector('bar');
})(document, window);
becomes
(function(a, b){
var c = a.body;
var d = a.querySelector('foo');
var e = a.querySelector('bar');
})(document, window);
If you did not place document and window in the function it'll just keep saying document;
(function(){
var c = document.body;
var d = document.querySelector('foo');
var e = document.querySelector('bar');
})();
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