JavaScript繼承方式

1.apply方法

apply方法詳情可以參考JavaScript中的apply和call

apply方法同樣也可以實現多繼承

示例代碼
function School(){
	this.name = 'HEU';
	this.showName = function(){
		console.log(this.name);
	}
}
function Unit(){
	this.uname = 'meituan.com';
	this.showUname = function(){
		console.log(this.uname);
	}
}

function Applyer(){
        //apply方法繼承School類和Unit類
	School.apply(this, arguments);
	Unit.apply(this, arguments);	
}

var me = new Applyer();
me.showName();
me.showUname();
運行結果


apply語句分別用School和Unit替代了Applyer中的this,成功的實現了繼承

也可以用call方法來實現

2.原型鏈方法

prototype對象是一個模板,要實例化的對象都以這個模板爲基礎,簡單地說,意思就是prototype對象的任何屬性和方法,都被傳遞給那個類的所有實例,原型鏈方法使用這種功能來實現繼承。

prototype的相關知識可以參考JavaScript中的對象與類


示例代碼

function Box(){
	this.size = 2;
	this.showSize = function(){
		console.log('the size is ' + this.size);
	};
}

function Package(){

}

Package.prototype = new Box();

var pack = new Package();
pack.showSize();

運行結果


在以上的代碼中,想要讓Package繼承Box的所有屬性和方法,我們把Package的prototype屬性設置爲Box的實例

注意:原型鏈不能實現多重繼承!

我們可以利用instanceof方法來確定原型和實例之間的關係

實例代碼
function Box(){
	this.size = 2;
	this.showSize = function(){
		console.log('the size is ' + this.size);
	};
}
function Box2(){

}
function Package(){

}

Package.prototype = new Box();

var pack = new Package();
pack.showSize();
console.log(pack instanceof Box);
console.log(pack instanceof Package);
console.log(pack instanceof Box2);

運行結果


3.混合方式

創建類的最好方式是用構造函數定義屬性,用原型定義方法,這種方法同樣適合於繼承機制。

示例代碼
function Fruit(season, weight){
	this.season = season;
	this.weight = weight;
}
Fruit.prototype.showMessage = function(){
	console.log(this.season);
	console.log(this.weight);
};

function Apple(season, weight, size){
	Fruit.call(this, season, weight);
	this.size = size;
}

Apple.prototype = new Fruit();
Apple.prototype.showMessage2 = function(){
	console.log(this.season);
	console.log(this.weight);
	console.log(this.size);
};

var apple = new Apple('spring', 3, 2);
var pear = new Fruit('summer', 4);
apple.showMessage();
console.log('\n');
apple.showMessage2();
console.log('\n');
pear.showMessage();

//用instanceof進行測試 觀察
console.log('\n');
console.log(pear instanceof Fruit);
console.log(pear instanceof Apple);
console.log(apple instanceof Apple);
console.log(apple instanceof Fruit);

運行結果




發佈了34 篇原創文章 · 獲贊 3 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章