An awkward way to execute JavaScript code

In a Google tutorial for embedding Google+ login in a Flask app, I found that a developer often uses an inconvenient way to execute JavaScript code:

Instead of doing

var a = foo(bar); 

I see it:

 var a = (function() { return foo(bar); })(); 

What is the reason for this strange way?

+53
javascript
Feb 03 '14 at 13:04
source share
3 answers

This is a bad example. Consider the following:

 var a = (function(){ var ret = {}; ret.test = "123"; function imPrivate() { /* ... */ } ret.public = function() { imPrivate(); } return ret; })(); 

a will contain a varible test and a public function, however you cannot access imPrivate. This is the usual way to handle public variables vs private;

See Why is this function terminated in parentheses and then parentheses? for more information.

+26
Feb 03 '14 at 13:12
source share
 var a = (function() { return foo(bar); })(); 

In this case, it really is not necessary, but it is not, and it will not cause an error.

But IIF uses it several times as a module pattern :

 var a = (function() { /* some other code in own scope */ return foo(bar); })(); 

In this case, IIF is simply a module that exports something outside.

+8
Feb 03 '14 at 13:08
source share

The close function is used to encapsulate some attributes / methods in the function. Largely as a private / public principle from other languages.

Further information can be found in this section here in the โ€œModule Structureโ€ section.

+2
Feb 03 '14 at 13:13
source share



All Articles