javascript繼承模式思考

來源:互聯網
上載者:User

雖說javascript沒有直接關鍵字或者符號實現對繼承的支援,我們同樣可以通過一些蹩腳的方式實現繼承。
方法一:
function Base(word) {
    this.say = function () {
        return word;
    }
    this.word = word;
}

function Sub(word) {
    this.hello = function () {
        return 'hello' + word;
    }
}
Sub.prototype = new Base();
Sub.prototype.constructor = Sub;
這個方法是我們最常見到的繼承方式,但是我們會注意到基類Base建構函式是需要一個word參數的,Sub 子類繼承Base時並無法將自己的word參數傳給基類。
new Sub().say() 得到的值永遠是undefined。
 
方法二:
function Base(word) {
    this.say = function () {
        return word;
    }
    this.word = word;
}

function Sub(word) {
    var base = new Base(word);
    base.hello = function(){ return 'hello' + word ; }
  reurn base;
}
var sub = Sub(word);
這個方法看起來比第一個方法簡單多了,也解決了傳參數的問題。
但是這個方法子類是var sub = Sub(word); 不像第一個方法 var sub = new Sub(word);
對於有new關鍵字強迫症的人,是不是看起來很糾結,這個寫法是不是總覺得Sub不像一個類。
 
方法三:
function Base(word) {
    this.say = function () {
        return word;
    }
    this.word = word;
}

function Sub(word) {
    $.extend(this, (new Base).constructor.apply(this, arguments)); // 調用Base 的constructor將初始化完的執行個體的屬性和方法都拷貝到this上面。
    this.hello = function () {
        return word;
    }
}
Sub.prototype = Base.prototype; // 保證 new Sub() instanceof Base == true
Sub.prototype.constructor = Sub; // 將contructor 設定成自己
這個寫法解決了第一個方法中無法為基類建構函式傳參的問題,也使類的執行個體化方式看起來更自然。
  但是我查了很多資料但是都沒看過 www.2cto.com
Sub.prototype = Base.prototype;

這種寫法,不知道是不是有什麼隱患。

 

摘自 flowforever

聯繫我們

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