我们经常在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 = {
}
function hhh(obj){
}
< /script>
< /head>
<body>
< input type="button" value="input.value"/>
< /body>
< /html>
运行以上的页面就很快明白了.
call和apply函数可以处理匿名函数
关于类的初始化应用如下:
Person = function(){
};
Person.prototype = {
};
var s = new Person2('creese', 'yang');
alert(s.fullName());
alert(s.fullNameReversed());
call和apply函数可以赋值函数内容(带匿名参数;但不触发)
关于函数绑定事件应用如下:
Function.prototype.BindForEvent = function() {
}
call和apply函数关于函数绑定参数应用如下:
Function.prototype.Bind = function() {
}
call和apply函数功能是一样的;就是参数格式不同;fun.call(obj, arguments);apply的arguments是数组形式;call则是单数形式。