这个javascript语法是什么意思? [英] What does this javascript syntax mean?
问题描述
我正在尝试理解由Asp.Net Ajax Toolkit生成的脚本,该脚本目前正在提供预期的对象(如果我将PopupControlExtender放在更新面板中,则错误消失)。
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);})();
我在这里看到的是:
someobject.someevent = function() {
dosth;
} /* Get ready, I am about to do sth crazy ... */
(function() { dosth; })(); /* you did what? */
这种语法是什么意思?
编辑:我特别好奇(function(){...})()在另一个函数的结束后立即出现}。
I am specifically curious about (function () { ... })() coming immediately after another function's ending }.
编辑:原来,ajax家伙忘记在事件处理程序分配后放置分号。
Turns out, ajax guys forgot to place a semicolon after the event handler assignment.
推荐答案
(function() { dosth; })();
语法声明一个匿名函数,然后立即执行它。这相当于这样做:
syntax declares an anonymous function, and then executes it immediately. It's equivalent to doing this:
var myFun = (function() { dosth; });
myFun();
但没有临时变量。
从广义上讲,这类似于执行任何 dosth
;但是创建一个函数对象会引入一个新的变量范围(由于闭包),因此这通常用于解决范围问题。
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.
在特定情况下你引用过,我认为没有任何理由说这一点特别必要。然而,它可以这样做有两个原因 - 最终的Javascript本身是由一些自动过程生成的,无法判断是否需要闭包;或者它是由一个决定永远把功能包装起来的人来写的。
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.
这篇关于这个javascript语法是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!