javascript call callee

來源:互聯網
上載者:User

call 能實作類別似的物件導向繼承:

function Person(){this.a = 'person';this.b = function(){alert('I\'m a person!');}this.c = 'Person\' c property';this.d = function(){alert('Person\' function d.');};}function Student(){Person.call(this);this.a = 'student';this.e = 'Student class';this.b = function(){alert('I\'m a Student');}this.f = function(){alert('This is Student\'s function.');}        //如果Person.call(this);放在這兒,則Person會覆蓋Student的方法 }function main(){var student = new Student();student.d();student.b();}main();

參考:

callee

    返回正被執行的 Function 對象,也就是所指定的
Function
對象的本文。

[function.]arguments.callee

可選項 function 參數是當前正在執行的 Function 對象的名稱。

說明

callee 屬性的初始值就是正被執行的 Function
對象。

callee 屬性是 arguments
對象的一個成員,它表示對函數對象本身的引用,這有利於匿名
函數的遞迴或者保證函數的封裝性
,例如下邊樣本的遞迴計算1到n的自然數之和。而該屬性
僅當相關函數正在執行時才可用。還有需要注意的是callee擁有length屬性,這個屬性有時候
用於驗證還是比較好的。arguments.length是實參長度,arguments.callee.length
形參長度,由此可以判斷調用時形參長度是否和實參長度一致。

樣本
比較一般的遞迴函式:調用時:alert(sum(100));
其中函數內部包含了對sum自身的引用,函數名僅僅是一個變數名,在函數內部調用sum即相當於調用
一個全域變數,不能很好的體現出是調用自身,這時使用callee會是一個比較好的方法。

//callee可以列印其本身
function calleeDemo() {
     alert(arguments.callee);
}
//用於驗證參數
function calleeLengthDemo(arg1, arg2) {
    if (arguments.length==arguments.callee.length) {
         window.alert("驗證形參和實參長度正確!");
        return;
     } else {
         alert("實參長度:" +arguments.length);
         alert("形參長度: " +arguments.callee.length);
     }
}
//遞迴計算
var sum = function(n){
  if (n <= 0)                        
  return 1;
  else
    return n +arguments.callee(n - 1)
}

var sum = function(n){
    if (1==n) return 1;
else return n + sum (n-1);

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.