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.
The
syntax declares an anonymous function, and then executes it immediately. It’s equivalent to doing this:
but without the temporary variable.
Broadly speaking this is similar to just executing whatever
dosthis; 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.