我們經常在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則是單數形式。