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

这段代码创建一个可拖曳移动的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 = "";
};
};
};
})();
-_-!!!

这是无名函名的调方式而已。

一个例子来说,如果你这样定义:
function Name(){};
调用时你可以使用Name();进行调用。在JS中存在一个无名函数的方法:
function () {};
这样一个函数你怎么调用?如果真的这样定义了除非是OOP,否则你永远没有机会调用不是?而OOP编程时会出现这种情况,如一个对象中定义这样的语句:
this.area = function (){};
这样也就是说我们定义了一个方法area,建立对象后可以使用“对象名.area();”这种形式进行调用。对于无名函数一般不想让别人误调用,而自己却只要调用一次时,可以将函数体加括号后看作一个对象进行立即执行。

也就是这种形式:
(function (){})();

严格来说,这是将定义与语句混写的形式。实际上它是一条语句,而不是一个定义。定义是后边没有分号的。如:
function () {}
而语句则后边是带;要求执行的!如:alert("1");这就是语句。为了有效地表达,所以这里使用了语句的形式,就是我们常说的无名函数的执行问题!
温馨提示:答案为网友推荐,仅供参考
第1个回答  2009-05-02
(函数( ) (
如果( typeof拖动! = “未定义” )

无功_Drag =拖曳;

/ / ? ˴ ?????拖? ?
/ / - elementid : Ҫ ? ž ? Ԫ ? ص ?编号
变种拖动= 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 = “ ” ;
) ;
) ;
) ;
})();
第2个回答  2009-05-02
() 立即调用该函数!
相似回答