这段js脚本最后面的一对圆括号是什么意思?

这段代码创建一个可拖曳移动的DIV,来自于JS外部文件中.
问题是,最前面的圆括号和最后面的一对圆括号有什么用?是否在JS外部文件中自定义函数或对象就需要这样定义,还是有其它的规则?请详细说明,谢谢!
(function(){
if(typeof Drag != "undefined")
{
var _Drag = Drag;
}
//此处声明Drag类
//--elementid:要移动元素的ID
var Drag = window.Drag = function(elementid){
var thisDrag = this;
this.DifWidth = 0;
this.DifHeight = 0;
this.thisDivDrag = document.getElementById(elementid);
this.thisDivDrag.onmousedown = function(event){
var theevent;
var theSrcevent;
if(window.event)
{
theevent = window.event;
theSrcevent = window.event.srcElement;
}
else
{
theevent =event;
theSrcevent =event.target;
}
thisDrag.DifWidth= theevent.clientX - theSrcevent.offsetLeft;
thisDrag.DifHeight = theevent.clientY - theSrcevent.offsetTop;
document.body.onmousemove =function(event){
var theevent;
if(window.event)
{
theevent = window.event;
}
else
{
theevent =event;
}
thisDrag.thisDivDrag.style.left = theevent.clientX -thisDrag.DifWidth ;
thisDrag.thisDivDrag.style.top = theevent.clientY -thisDrag.DifHeight ;
};
document.body.onmouseup =function(event)
{
document.body.onmousemove = "";
};
};
};
})();
0_0

这属于js匿名函数的一种!
这种写法可以看做是私有的内部类,一般出于加载时就需要立即执行的代码可以这样来些,第2个就是避免与其它的名称相冲突.
给你举个例子看看:
(function(p1,p2){alert(p1+p2);})(1,2);
实际就相当与
function test(p1,p2){
alert(p1+p2);
}
test(1,2);
(function(){})();
匿名方法的好处,上面也有提到.
1.其它外部调用不到,相对安全.
2.可用于onload事件保证不与其冲突.
3.可看做线程安全.曾经做项目时遇到过一个循环读取值的问题,每次得到的都是第一个值,最后用该函数解决的.

下面介绍一下它的调用
var fnc = function(){alert('x');},这里function如果不赋值给fnc那么它就是一个匿名函数,这种函数我们称为回调函数.调用方式fnc();

下面是匿名函数的调用。
有返回值的调用函数
得到返回值。强制运算符使函数调用执行
<1>
(function(p1,p2){
return p1+p2;
}(1,2));

强制函数直接量执行再返回一个引用,引用在去调用执行
<2>
function(p1,p2){
return p1+p2;
})(1,2);

无返回值的调用
<3>
void function(p1) {
return p1++;
}(2);

测试function test(){
return (function(p1,p2){
return p1+p2;
})(1,2);
//等以上几种情况.
}
alert(test());
结果33undefined
温馨提示:答案为网友推荐,仅供参考
第1个回答  2009-05-02
"()" 代表函数.。

函数() (
如果( typeof拖动! = “未定义” )

无功_Drag =拖曳;


变种拖动= window.Drag =功能( elementid ) (
无功thisDrag =这;
this.DifWidth = 0 ;
this.DifHeight = 0 ;
this.thisDivDrag = document.getElementById ( elementid ) ;
this.thisDivDrag.onmousedown =功能(活动) (
无功theevent ;
无功theSrcevent ;
如果( window.event )

theevent = window.event ;
theSrcevent = window.event.srcElement ;

其他的

theevent =活动;
theSrcevent = event.target ;

thisDrag.DifWidth = theevent.clientX - theSrcevent.offsetLeft ;
thisDrag.DifHeight = theevent.clientY - theSrcevent.offsetTop ;
document.body.onmousemove =功能(活动) (
无功theevent ;
如果( window.event )

theevent = window.event ;

其他的

theevent =活动;

thisDrag.thisDivDrag.style.left = theevent.clientX - thisDrag.DifWidth ;
thisDrag.thisDivDrag.style.top = theevent.clientY - thisDrag.DifHeight ;
) ;
document.body.onmouseup =功能(活动)

document.body.onmousemove = “ ” ;
) ;
) ;
) ;
})();
相似回答