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

后端 未结 3 1383
南笙
南笙 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.

提交回复
热议问题