js面向对象的3种继承方式总结

创建一个人类然后继承学生类

1.原型继承:People继承Student,将Student对象赋值在People的原型上,代码举例如下:

function Student(name,age){
      this.name=name
      this.age=age
}
Student.prototype.task=function(){
      console.log(this.name+"的主要任务是上学")
}
function People(name,age){
      //构造函数里无内容,传入的参数无效
}
People.prototype=new Student("tom",21)
var p1=new People("marry",21);
var p2=new People("jerry",22);
console.log(p1.name,p2.name);

上段代码的输出结果都是tom,说明了无法改变People.prototype=new Student("tom",21)这句代码的入参

2.冒充继承:通过call或apply来更改对应的this指向达到继承目的

function Student(name,age){
     this.name=name
     this.age=age
}
Student.prototype.task=function(){
     console.log(this.name+"的主要任务是上学")
}
function People(name,age){
     Student.call(this,name,age);
}
var p=new People("marry",21);
console.log(p.name);
p.task();

运行代码,控制台输出结果为:

 说明冒充继承无法继承父类的原型中的方法

3.混合继承:原型继承+冒充继承

function Student(name,age){
     this.name=name
     this.age=age
}
Student.prototype.task=function(){
     console.log(this.name+"的主要任务是上学")
}

function People(name,age){
     Student.call(this,name,age);//通过call或apply来更改对应的this指向new出来的实例对象p
}
People.prototype=new Student();//将Student的原型继承过来,可继承原型中的方法
var p=new People("marry",21);
console.log(p.name);
p.task();

控制台输出的结果为:

 通过这种方式,子类能完全继承父类的构造函数以及原型上的方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值