What does javascript syntax mean?

I am trying to understand the script generated by the Asp.Net Ajax Toolkit that currently gives the "expected object" (the error disappears if I put the PopupControlExtender in the 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:

 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 particularly interested in (function () {...}) (), which appears immediately after the end of another function}.

Edit: It turns out the ajax guys forgot to place a semicolon after assigning an event handler.

+4
source share
4 answers

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

declares an anonymous function and then executes it immediately. This is equivalent to this:

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

but without a temporary variable.

In a broad sense, this is like doing all of dosth ; but creating a function object introduces a new scope for variables (due to closure), and thus it is often used to solve problems using scope.

In the specific case that you quoted, I see no reason why this would be especially necessary. However, this can be done for two reasons: either the last Javascript itself is generated by some automatic process that cannot determine if closing is required; or it was written by a person who decided to always wrap things in functions to be safe.

+5
source
 (function() { dosth; })(); 

An anonymous function is created here, and then immediately called.

This is a relatively popular idiom for creating a local area in JavaScript, where only functions get their own area.

The local scope allows you to have private variables and avoid name conflicts.

In other languages ​​you can write something like

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

and all three variables will be in different areas, but in JavaScript you have to declare a function to get a new area.

+2
source
 (function() { dosth; })(); 

wraps dosth in an anonymous function and then runs that anonymous function as soon as the page loads (what do these final () do)

+1
source

Assuming you mean this:

 (function() { dosth; })(); /* you did what? */ 

This declares an anonymous function in the first parens block, which will be the returned object from this pair block executed by the second block of pairs.

Thus, it defines and accomplishes everything that is "available."

0
source

All Articles