这段代码创建一个可拖曳移动的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 = "";
};
};
};
})();
问题是,最前面的圆括号和最后面的一对圆括号有什么用?是否在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 = "";
};
};
};
})();
这个,能详细说下第一对和最后一对圆括号的意义或作用吗?
我试了下,这两对括号都不能少,否则就会报错.
谢谢!
那么本例中最后的括号就相当于 xxx()中的括号。
由此推断 function(){} 就相当于 xxx,即定义了函数的句柄。
在本例中, function(){}之外又套用了一个(), 即(function(){})
()是高优先级,用于优先计算其中的值,就相当于先定义函数,定义好以后马上调用.不是一定要这样做,一般的定义可以
function xxx(){}
然后调用
xxx();
这样比较清楚.