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

后端 未结 3 1335
南笙
南笙 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 01:49

    It's just a select calling function. The () at the end causes it to be called automatically.

    It's used like this to isolate local variables that are relevant only to your code from the global scope.

    For example:

    (function() {
    
       var x = 5;
       window.y = 6;
    
    })();
    

    x is available only in the scope of the function, y is globally available through the window.

    As to it not running, I'd hazard that's down to the conditional you supplied.

    0 讨论(0)
  • 2021-01-22 02:04

    The "function(){code}" part only creates a function, the () at the end call the created function. You could rewrite

    (function() {
    code
      })();
    

    As

    var x = function() {code};
    x();
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题