建構函式 繼承

2021-08-07 10:00:08 字數 1633 閱讀 2552

首先給出如下兩個建構函式

function animal()

function cat( name, color)

一、建構函式的繫結

function cat( name, color)

var cat11 = new cat("11", "綠色");

console.log(cat11.species);

二、prototype 模式

cat的prototype 物件指向乙個animal的例項,所有貓的例項都能繼承animal

// 如果替換prototype物件,下一步需要將這個新的prototype物件加上constructor屬性,並指向原來的建構函式

cat.prototype = new animal();

cat.prototype.constructor = cat;

var cat13 = new cat("大毛", "黃色");

console.log(cat13.species);

三、直接繼承prototype

需要將animal 改寫

function animal()

animal.prototype.species = "動物";

cat.prototype = animal.prototype;

cat.prototype.constructor = cat;

var cat14 = new cat("14", "黃色");

這樣做有點是效率高,缺點是cat.prototype 和 animal.prototype 指向同乙個物件,任何對cat.prototype 的修改 都會直接影響 animal.prototype 的修改

四、利用空物件作為中介

var p = function() {};

p.prototype = animal.prototype;

// cat的prototype指向p的例項,cat的例項可以繼承p

// 相當於刪除了原先的值,然後賦予了乙個新值

cat.prototype.constructor = cat;

封裝成函式

function extend(child, parent) ;

p.prototype = parent.prototype;

child.prototype = new p();

child.prototype.constructor = child;

//備用方法

cat.uber = parent.prototype;

}extend(cat, animal);

var cat = new cat("小貓", "公尺色");

五、拷貝

function extend(child, parent)  

c.uber = p;

}extend( cat, animal);

注:參考阮一峰

建構函式 繼承

首先給出如下兩個建構函式 function animal function cat name,color 一 建構函式的繫結 function cat name,color var cat11 new cat 11 綠色 console.log cat11.species 二 prototype 模...

繼承建構函式

在c 的繼承關係中,只有虛函式可以被繼承,而建構函式不可以是虛函式,所以建構函式不能被繼承,但是可以通過某種特殊手段,達到繼承的效果。先看看c 中using關鍵字的乙個應用 1 include 2 using namespace std 34 struct base 6 78struct deriv...

建構函式的繼承

在父類中定義了2個建構函式,在子類中,也定義了2個建構函式。當執行子類時,可以發現先呼叫父類的建構函式,在呼叫子類的建構函式。實驗四 建構函式的繼承 實驗內容 在父類中,定義了2個建構函式,在子類中,也定義了2個建構函式。編寫 程式顯示父類 子類建構函式的呼叫過程,在子類中實現建構函式的繼承。pac...