经典的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) // 王

如有问题,欢迎大家指出,一起成长,哈哈。

猜你喜欢

转载自blog.csdn.net/xiaoxiaojie12321/article/details/81289109