JavaScript中的繼承的入門知識

來源:互聯網
上載者:User

許多OOP語言都支援兩種繼承方式:介面繼承和實現繼承。介面繼承只繼承方法簽名,而實現繼承則繼承實際的方法。由於函數沒有簽名,在ECMAScript中無法實現介面繼承。ECMAScript只支援實現繼承,而且其實現繼承主要是依靠原型鏈來實現的。

實現對象整合集中方法如下:

一. 原型鏈繼承

使用原型鏈整合的基本思想,是利用原型讓一個參考型別整合另一個參考型別的屬性和方法。

本質就是重寫原型對象,代之以一個新類型的執行個體。

function SuperType() {
    this.property = true;
}

SuperType.prototype.getSuperValue = function() {
    return this.property;
}

function SubType() {
    this.subProperty = false;
}

// 繼承了SuperType
SubType.prototype = new SuperType();
SubType.prototype.getSubValue = function() {
    return this.subProperty;
}

var instance = new SubType();
alert("Sub: " + instance.getSubValue());
alert("Super: " + instance.getSuperValue());
原型鏈雖然很強大,但是用它來實現繼承,最主要的問題來自包含參考型別值的原型。參考型別值的原型屬性會被所有執行個體共用。

function SuperType() {
    this.colors = ["red", "blue", "green"];
}

function SubType() {}

SubType.prototype = new SuperType();

var instance1 = new SubType();
instance1.colors.push("black");
console.log(instance1.colors); // "red", "blue", "green", "black"

var instance2 = new SubType();
console.log(instance2.colors); // "red", "blue", "green", "black"
所以,在實踐中,很少會單獨使用原型鏈。

二. 借用建構函式

借用建構函式技術也叫做偽造對象,或經典繼承。基本思路是在子類型建構函式的內部調用超類型建構函式。

函數只是在特定環境中執行代碼的對象,因此通過使用apply()和call()方法,也可以在新建立的對象上執行建構函式。

function SuperType() {
    this.colors = ["red", "blue", "green"];
}

function SubType() {
    SuperType.call(this);
}

var instance1 = new SubType();
instance1.colors.push("black");
console.log(instance1.colors); // "red", "blue", "green", "black"

var instance2 = new SubType();
console.log(instance2.colors); // "red", "blue", "green"
使用call()方法(或apply()方法),實際上是在新建立的SubType執行個體的環境下調用了SuperType建構函式。

相對於原型鏈而言,借用建構函式有一個很大的優勢,就是可以在子類型建構函式中向超類型建構函式傳遞參數。例如:

function SuperType(name) {
    this.name = name;
}

function SubType() {
    SuperType.call(this, "Hello world");
    this.age = 12;
}

var instance = new SubType();
alert(instance.name); // "Hello world"
alert(instance.age); // 12
由於在超類型中定義的方法,對於子類型而言是不可見的,結果所有類型都只能使用建構函式模式。因此借用建構函式的技術也很少單獨使用。

三. 組合繼承

【努力施工中…】

四. 寄生式繼承

【努力施工中…】

五. 寄生組合式繼承

聯繫我們

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