我们经常在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 : 'self.value',
exec : function(){
alert(this.value);
}
}
function hhh(obj){
test.exec();
test.exec.apply(obj);
}
< /script>
< /head>

<body>
< input type="button" value="input.value"/>
< /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则是单数形式。