Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this javascript syntax mean? [duplicate]

I am trying to understand a script generated by Asp.Net Ajax Toolkit, which is currently giving an "object expected" (error goes away if I place my PopupControlExtender in an update panel).

document.getElementById('ctl00_ValidationSummary1').dispose = function() {
    Array.remove(Page_ValidationSummaries, document.getElementById('ctl00_ValidationSummary1'));
}
(function() {var fn = function() {AjaxControlToolkit.ModalPopupBehavior.invokeViaServer('ctl00_c1_componentCategoryListUC_componentCategoryGrid_modalPopupExtender', true); Sys.Application.remove_load(fn);};Sys.Application.add_load(fn);})();

What I see here is:

someobject.someevent = function() {
    dosth;
} /* Get ready, I am about to do sth crazy ... */
(function() { dosth; })(); /* you did what? */

What does this syntax mean?

Edit: I am specifically curious about (function () { ... })() coming immediately after another function's ending }.

Edit: Turns out, ajax guys forgot to place a semicolon after the event handler assignment.

like image 209
Serhat Ozgel Avatar asked Mar 02 '23 00:03

Serhat Ozgel


2 Answers

The

(function() { dosth; })();

syntax declares an anonymous function, and then executes it immediately. It's equivalent to doing this:

 var myFun = (function() { dosth; });
 myFun();

but without the temporary variable.

Broadly speaking this is similar to just executing whatever dosth is; but creating a function object introduces a new scope for variables (due to the closure), and thus this is often used to work around issues with scoping.

In the specific case you've quoted, I don't see any reason why this would be particularly necessary. However it could be done like this for two reasons - either the final Javascript itself is generated by some automatic process that can't tell whether the closure is needed; or it was written by a human who decided to always wrap things in functions to be safe.

like image 51
Andrzej Doyle Avatar answered Mar 08 '23 23:03

Andrzej Doyle


(function() { dosth; })();

Here, an anonymous function is created, and then immediately invoked.

This is a relatively popular idiom to create a local scope in JavaScript, where only functions get their own scope.

A local scope allows you to have private variables and avoids name clashes.

In other languages you could write something like

int a = 1;
{
   int b = 0;
   if (something){
       int c = 3;
   }
}

and the three variables would all be in separate scopes, but in JavaScript you have to declare a function to get a new scope.

like image 37
Thilo Avatar answered Mar 08 '23 23:03

Thilo