OOP with JavaScript(一) OOP的基本文法

來源:互聯網
上載者:User
javascript是一門太過靈活的函數語言,其語言機制本身並沒有提供完
整的物件導向實現(沒有類,繼承等概念),但憑藉其靈活的文法,仍
然可以在一定程度上實現OOP。

比如類的概念,可以通過以下文法來實作類別TestA:
TestA = function(nValue) {
    this.m_nValue = nValue;
    this.funcA = function() {
        alert("funcA:" + this.m_nValue);
    }
}

TestA類的使用方法如下:
a = new TestA(100);
a.funcA();

在函數語言的基礎上,實現OOP的繼承需要一些特殊的文法,
在《Professional.JavaScript.For.Web.Developers》一書中,
列舉了多種繼承的實現文法,網上最常用的是這種:
TestB = function() {
    this.funcB = function() {
        alert("funcB");
    }
}

TestB.prototype = new TestA(100);

但是這樣的文法對於帶參數的類構造不太適用,我喜歡用下面這種
TestB = function(nValue) {
    this.superContructor = TestA;
    this.superContructor(nValue);
   
    this.funcB = function() {
        alert("funcB");
    }
}

繼承實現了,那函數重載怎麼做呢,很簡單
TestB = function(nValue) {
    this.superContructor = TestA;
    this.superContructor(nValue);
   
    this.funcB = function() {
        alert("funcB");
    }

    /*    重載父類的funcA函數    */
    this.funcA = function() {
        alert("funcA overrided by TestB:" + this.m_nValue);
    }
}

如果重載了funcA,但是還需要調用父類的函數(類似C++中的顯示調用CTestA::funcA()),
可以用以下方法:
TestB = function(nValue) {
    this.superContructor = TestA;
    this.superContructor(nValue);
   
    this.funcB = function() {
        alert("funcB");
    }

    /*    重載父類的funcA函數,同時在子類的實現中再調用父類的原實現函數    */
    this.super_funcA = this.funcA;
    this.funcA = function() {
        if ((this.m_nValue % 2) == 0)  {
            alert("funcA overrided by TestB:" + this.m_nValue);
        }
        else {
            this.super_funcA();
        }
    }
}

除了這些基本的OOP功能之外,javascript作為一門動態語言,還支援動態構造一個類或者函數:
for (var i = 0; i<10; i++) {
    eval("function test_func" + i + "() { alert (" + i + "); }");
}

上面的代碼動態構造了10個函數,分別名為test_func0到test_func9,其功能是分別顯示0到9的數字。
這樣的文法和C/C++的宏或者模板相比,靈活度提高了非常多。

這個功能在dhtml中特別有用,對於動態產生的dhtml對象,可以動態建立其對應的event函數。

(待續...)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.