What's the technique that the Google analytics tracking code uses?

后端 未结 3 1384
南笙
南笙 2021-01-22 01:14

The Google Analytics tracking code looks like this:

(function() {
code
  })();

What\'s the technique they are using with those brackets -

3条回答
  •  难免孤独
    2021-01-22 02:06

    (function() {
       /* code */
    }()); 
    

    It's commonly known as «self executed anonymous function (¹)» (o «immediate function invocation») and its main use is to avoid the creation of variables into the global (or in the outer) scope.

    It's also used as shortcut when you want to create a function to execute just once, without the need to first define the function with its own identifier and then soon make the function call.

    It may be eventually used inside a scope and then it may create a closure if the outer context (or other references) are binded through parameters passing, e.g.

    /* outer scope */  
    (function(outerscope) {
    
       element.onsomeevent = function() {
           /* do something with outerscope */
       };
    
    }(this));
    

    Another practical use I make with this expression is when I need to create a function to be soon executed inside a constructor function when it is called with new keyword (instead of an explicit call to some init method).


    (¹) — as stated on book "Mantainable Javascript" by Nicholas Zakas (O'Reilly, ISBN 978-1-449-32768-2) page 44, the suggested expression is (function() {}()), with nested parens (even if (function() {})() will work anyway)

    [...]To make it obvious that immediate function invocation is taking place, put paretheses around the function[...]

    See also Immediate function invocation syntax

提交回复
热议问题