js中實現多態

來源:互聯網
上載者:User

標籤:繼承   多態   類   js   function   

        多態的實現可以採用和繼承類似的方法。首先定義一個抽象類別,其中調用一些虛方法,虛方法在抽象類別中沒用定義,而是通過其具體的實作類別來實現。

如下面的例子:

Object.extend=function(destination,source){for(property in source){destination[property]=source[property];}return destination;}//定義一個抽象基類base,無建構函式function base(){};base.prototype={    initialize:function(){    this.oninit();//調用了一個虛方法    }}function SubClassA(){//建構函式}SubClassA.prototype=Object.extend({propInSubClassA:"propInSubClassA",oninit:function(){alert(this.propInSubClassA);}},base.prototype);function SubClassB(){//建構函式}SubClassB.prototype=Object.extend({propInSubClassB:"propInSubClassB",oninit:function(){alert(this.propInSubClassB);}},base.prototype);var objA=new SubClassA();objA.initialize();//輸出"propInSubClassA"var objB=new SubClassB();objB.initialize();//輸出"propInSubClassB"

        首先定義了一個抽象基類base,在base類的initialize方法中調用了oninit方法,但是基類中並沒用oninit方法的實現或者聲明。SubClassA和SubClassB類繼承自base類,並且分別採用了不同的方式對oninit方法進行實現。

聯繫我們

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