js中call,apply,setCapture,releaseCapture的使用

  • 页面元素拖拽 -- HTML中的setCapture和releaseCapture

setCapture函数的作用就是将后续的mouse事件都发送给这个对象,releaseCapture就是将鼠标事件还回去,由 document、window、object之类的自行来处理,这样就保证了在拖动的过程中,不会由于经过了其它的元素而受到干扰。另外,还有一个很重 要的事情是,在Win32上,mouse move的事件不是一个连续的,也就是说,并不是我们每次移动1px的鼠标指针,就会发生一个mousemove,windows会周期性检查mouse 的位置变化来产生mousemove的事件。所以,如果是一个很小的页面对象,比如一个直径5px的圆点,如果没有setCapture和 releaseCapture,那么在鼠标按住之后,快速的移动鼠标,就有可能鼠标移动走了,但是小圆点还在原地,就是因为下一次的mousemove事 件已经不再发给这个圆点对象了。

  • 关于javascript中call和apply函数的应用
我们经常在javascipt中的面向对象应用中遇到call和apply函数;有时会被搞糊涂。其实它们可以改变函数或对象中的this保留字的值;this保留字的默认值就是这个类本身。举例说明:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<script language="javascript">
test = {
 value : 'default',
 exec  : function(){
  alert(this.value);
 }
}
function hhh(obj){
  test.exec();
  test.exec.apply(obj);
}
</script>
</head>

<body>
<input type="button" onclick="hhh(this);" value="test"/>
</body>
</html>

运行以上的页面就很快明白了.

 

call和apply函数可以处理匿名函数

关于类的初始化应用如下:

Person = function(){
 this.Init.apply(this, arguments);
};
Person.prototype = {
 first : null,
 last : null,
 Init : function(first, last){
    this.first = first;
    this.last = last; 
 },
 fullName : function(){
    return this.first + ' ' + this.last; 
 },
 fullNameReversed : function(){
    return this.last + ', ' + this.first;  
 }
};

var s = new Person2('creese', 'yang');
alert(s.fullName());
alert(s.fullNameReversed());

 

call和apply函数可以赋值函数内容(带匿名参数;但不触发)

关于函数绑定事件应用如下:

Function.prototype.BindForEvent = function() {
  var __m = this, object = arguments[0], args = new Array();
  for(var i = 1; i < arguments.length; i++){
  args.push(arguments[i]);
 }
  return function(event) {
    return __m.apply(object, [( event || window.event)].concat(args));
  }
}

call和apply函数关于函数绑定参数应用如下:

Function.prototype.Bind = function() {
  var __m = this, object = arguments[0], args = new Array();
  for(var i = 1; i < arguments.length; i++){
  args.push(arguments[i]);
 }
  return function() {
    return __m.apply(object, args);
  }
}

call和apply函数功能是一样的;就是参数格式不同;fun.call(obj, arguments);apply的arguments是数组形式;call则是单数形式。

posted @ 2008-09-23 16:22  joinger  阅读(1067)  评论(0编辑  收藏  举报