【JS】继承模式

我们知道在es6中我们使用extend实现继承,当然在我们也可以使用js实现面向对象的继承

传统方式--原型链

Grand.prototype.lastName="shu";
function Grand(){


}
var grand =new Grand();
Father.prototype=grand;
function Father(){


}
var father=new Father();
console.log(father.lastName);
//shu

通过使用原型链可以实现继承,但是它过多的继承了没有用的属性,很快就离开了继承的舞台。

借用构造函数

function Father(lastName,age,sex) {
    this.lastName='shu';
    this.sex='male';
    this.age=38
}

function Son(lastName,sex,age) {

    Father.call(this,lastName,sex);
    this.age=18
}

var son =new Son();

console.log(son);

// {
//   age:18
//   lastName:"shu"
//   sex:"male"
// }

解决了上面的缺点,但是出现了新的问题,只能继承构造函数,并不能继承构造函数的原型,且每次都需要调用浪费性能

共享原型

Grand.prototype.lastName="shu";
function Grand(){

}

function Father(){

}
Father.prototype=Grand.prototype
var father =new Father();
console.log(father.lastName);
//shu
令Father的原型地址指向Grand的原型地址,可以较好的实现继承,下面我们可以封装一个方法实现这种继承
function inherit(Target,Origin){
	Target.prototype=Origin.prototype;
}

但是后续在Father上添加原型方法或属性时候,Grand也会有这个方法或属性。

圣杯模式

Father.prototype.lastName="shu";
function Father(){

}

function Son(){

}
function F(){

}
F.prototype=Father.prototype;
Son.prototype=new F();
var son =new Son();
console.log(son.lastName);
//shu
我们可以通过一个中间函数,使用原型链的方法完成这个继承的交接,接下来我们就可以在Son上添加属性方法,而不会在影响Father了。我们继续来封装这个方法
function inherit(Target,Origin){
	function F(){}
	F.prototype=Origin.prototype;
	Target.prototype=new F();
	Target.prototype.constuctor=Target;
	Target.prototype.uber = Origin.prototype   //保存了它的超类(也就是它真正继承的对象)
}
这个继承模式是现在比较完善的。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值