Friday, May 24, 2019

Awkward way of executing JavaScript code




In the Google tutorial for implementing Google+ sign-in in Flask application, I discovered that the developer often uses an awkward way of executing JavaScript code:




Instead of doing



var a = foo(bar);


I see this:



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



What is the reason to do it the weird way?


Answer



This is a poor example. Consider the following:



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

ret.public = function() { imPrivate(); }
return ret;
})();


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



See Why is this function wrapped in parentheses, followed by parentheses? for more info.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...