天天看點

經典的JavaScript繼承模式

了解JavaScript繼承有助于平時的開發,下面談談四種經典繼承模式。

1.原型鍊 

缺點:屬于傳統繼承模式,把構造函數和原型都繼承過來了

Father.prototype.lastName = "王";
function Father (sex) {
	this.sex = sex
}
function Son () {}
var father = new Father("男");
Son.prototype = father;
var son = new Son();
console.log(son.lastName) // 王
console.log(son.sex) // 男
           

2.借用構造函數

缺點: 不能繼承借用構造函數的原型

function Father (lastName) {
	this.lastName = lastName
}

function Son (lastName) {
	Person1.Father(this, lastName)
}

var son = new Son("王")
console.log(son.lastName) // 王
Father.prototype.lastName = "趙"
console.log(son.lastName) // 王
           

3.共享原型

缺點:隻要其中一個對象原型改變時,其他對象會受到影響

Father.prototype.lastName = "王";
function Father () {}
function Son () {}
Son.prototype = Father.prototype;
var son = new Son();
var father = new Father();
console.log(son.lastName); // 王
console.log(father.lastName); // 王
son.prototype.lastName = "趙";
console.log(son.lastName); // 趙
console.log(father.lastName); // 趙
           

4.聖杯模式

優點:有利于繼承父對象的原型和屬性,而當子對象的原型改變使,父對象不受其影響

function inherit (Target, Origin) {  // Target繼承Origin
	function F () {}; // 中間構造函數
	F.prototype = Origin.prototype; 
	Target.prototype = new F(); // 使Target繼承于F的執行個體對象,進而使Target和Origin之間互不幹擾
	Target.prototype.constuctor = Target;
}

function Father () {};
function Son () {};
inherit(Son, Father)

var son = new Son();
var father = new Father();
Father.prototype.lastName = "王";
console.log(son.lastName) // 王
console.log(father.lastName) // 王

son.lastName = "趙";
console.log(son.lastName) // 趙
console.log(father.lastName) // 王
           

如有問題,歡迎大家指出,一起成長,哈哈。

繼續閱讀