Javascript, which uses a function call like this (function () {// code;}) ();

Possible duplicates:
Is the following JavaScript construct called Closure?
What do the parentheses associated with declaring a JavaScript object / object / class mean?
How does the constructor (function () {}) () work and why do people use it?
The difference between (function () {}) (); and function () {} ();

Hi,

As I was browsing a site with plain html text and no graphics, I thought about viewing its code.

When I did this, I found this script

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-13137273-2']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>

is there any specific purpose for using code like the following

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

I saw this in jquery. But still, I don't really like the free javascript extreme style of programming.

, . .

[ . ... , . , javascript , . , .]

+3
3

javascript - , .

( ) :

var foo = function(){return 4;}
var x = foo(); //x=4

foo(); function(){return 4;}();. , javascript, , javascript .

. , , ..


: , , , . {...} C ((lambda () ...)) .

+4

, :

<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-13137273-2']);
  _gaq.push(['_trackPageview']);

  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
</script>

, ga s . - , . , , , , s -, - , .

- " ?" . .

+8

It limits the scope of variables declared inside a function to avoid clogging the global namespace.

This is a common practice, and there is nothing extreme about it.

+7
source

Source: https://habr.com/ru/post/1779720/


All Articles