What to do with empty parentheses () after function declaration in javascript?

I am trying to read the source of Prototype. I came to this part. (Unfortunately, this fragment is at the beginning).

What does it mean()?

Browser: (function(){ var ua = navigator.userAgent; var isOpera = Object.prototype.toString.call(window.opera) == '[object Opera]'; return { IE: !!window.attachEvent && !isOpera, Opera: isOpera, WebKit: ua.indexOf('AppleWebKit/') > -1, Gecko: ua.indexOf('Gecko') > -1 && ua.indexOf('KHTML') === -1, MobileSafari: /Apple.*Mobile.*Safari/.test(ua) } })(), 

I mean the last line before the comma?

+50
javascript
Mar 11 '10 at 1:52
source share
4 answers

The code defines an anonymous function (bit (function (){ ... }) ), and then calls it (without arguments). It then assigns a value to the Browser property of the object, which is supposedly defined outside the code snippet.

You can also define a function somewhere:

 function myFunction() { var ua = navigator.userAgent; var isOpera = Object.prototype.toString.call(window.opera) == '[object Opera]'; return { IE: !!window.attachEvent && !isOpera, Opera: isOpera, WebKit: ua.indexOf('AppleWebKit/') > -1, Gecko: ua.indexOf('Gecko') > -1 && ua.indexOf('KHTML') === -1, MobileSafari: /Apple.*Mobile.*Safari/.test(ua) } 

and then name it:

 var foo = myFunction(); 

and then assign the value:

 ... Browser: foo, ... 

One of the drawbacks is that you "pollute the namespace" with a function and variable that you will no longer use. The second problem is that you cannot use the value of any locally restricted variables in the definition of a function (an anonymous function behaves like a closure).

+39
Mar 11 2018-10-11T00:
source share

(function () {}) creates an anonymous function.

Adding () to the end calls the function that was just created.

In the case of this particular function, an anonymous function returns several properties to the Browser object. This way you get boolean values ​​for e.g. Browser.IE , Browser.Opera , etc.

+26
Mar 11 2018-10-11T00:
source share

it calls an anonymous function that has just been declared, which actually leads to an evaluation of the "block".

+11
Mar 11
source share

This is a simple function call other than foo() , except that it calls a literal of an anonymous function, the result of the function is assigned to the Browser property.

+5
Mar 11
source share



All Articles