Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self invoking anonymouse functions with document parameter

Tags:

javascript

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?

like image 754
tommyd456 Avatar asked Jan 06 '23 00:01

tommyd456


1 Answers

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');
})();
like image 113
Erik Terwan Avatar answered Jan 07 '23 12:01

Erik Terwan