javaScript继承

简单说一下继承

  • 继承是面向对象开发思想的特性之一。
  • 面向对象的三大特点:封装、继承、多态
  • 继承主要分ES5和ES6的继承方式

ES5的继承(主要通过函数实现类)

  • 原型链继承 主要实现代码
//创建一个父类
function Parent() {
    this.name='jack'
}

Parent.prototype.getName=function() {
    return this.name;
}

//创建一个子类
function Child() {
   
}
//子类的原型等于父类的实例化对象
Child.prototype=new Parent();
var c1=new Child()

缺点: 不能传参
没有解决对象的引用问题

  • 借用构造函数继承
//创建一个父类
function Parent(name) {
    this.name=name ||'jack'
    this.colors=['red','green','blue']
}

Parent.prototype.getName=function() {
    return this.name;
}

//创建一个子类
function Child(name) {
    //借用父类来承继实例属性,但不能继承父类方法
    Person.call(this,name) 
}

缺点: 不能继承父类方法

  • 组合继承 = 原型链继承 + 借用构造函数继承
//创建一个父类
function Parent(name) {
    this.name=name ||'jack'
    this.colors=['red','green','blue']
}

Parent.prototype.getName=function() {
    return this.name;
}

var p1=new Parent();
p1.getName();

//创建一个子类
function Child(name) {
    Parent.call(this,name)   
}
Child.prototype=new Parent();
var c1=new Child()
c1.getName()

优点:即能继承父类的原型方法,也能传递参数属性

ES6继承(通过class、extends、super实现)

//创建一个父类
class Parent {
   constructor(name) {
        this.name=name ||'jack'
        this.colors=['red','green','blue']
   }

  getName() {
    return this.name;
}
}


//创建一个子类
 class Child extends Parent {
      constructor(name) {
          super(name)  //super就是父类Parent
      }
      getValue() {

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值