ES5、ES6继承

ES5、ES6继承方式

继承的目标:

  • 父类公有属性和方法为子类公有属性和方法
  • 父类私有属性和方法为子类私有属性和方法

1. ES5继承

  • 原型继承
  // 定义父类
  function Parent(){
    this.familyName = "Corleone"
  }

  Parent.prototype.skill = ()=>{
    return "保护家人"
  }

  // 定义子类
  function Child(){
    this.name = "Michael"
  }

  // 将子类原型指向父类实例
  Child.prototype = new Parent()
  Child.prototype.constructor = Child

  // 注意:定义子类原型方法要在改变原型指向之后再定义
  Child.prototype.ability = ()=>{
    return "有勇有谋"
  }

  let michey = new Child()
  console.log(michey.name, michey.familyName, michey.skill(), michey.ability())
  // Michael Corleone 保护家人 有勇有谋

原型继承是将子类原型指向父类实例从而继承父类公有和私有的属性、方法。缺陷是父类公有和私有都变成了子类公有。

  • .call() 寄生继承
  // 定义父类
  function Parent(){
    this.familyName = "Corleone"
  }

  Parent.prototype.skill = ()=>{
    return "保护家人"
  }

  // 定义子类
  function Child(){
    this.name = "Michael"
    // 将父类构造函数当做普通函数来执行,同时改变this 指向
    Parent.call(this)
  }

  // 注意:定义子类原型方法要在改变原型指向之后再定义
  Child.prototype.ability = ()=>{
    return "有勇有谋"
  }

  let michey = new Child()
  console.log(michey.name, michey.familyName, michey.skill(), michey.ability())
  // Michael Corleone 保护家人 有勇有谋

寄生继承是在子类构造函数内将父类构造函数当做普通函数执行,同时改变this 指向,指向子类完成继承。缺陷是父类的公有和私有属性、方法均为子类私有。

  • 组合式继承(.call() + Object.create)

Object.create() 方法创建一个空对象,第一个参数会把创建的空对象的__proto__指向传入的参数对象

  // 定义父类
  function Parent(){
    this.familyName = "Corleone"
  }

  Parent.prototype.skill = ()=>{
    return "保护家人"
  }

  // 定义子类
  function Child(){
    this.name = "Michael"
    // 将父类构造函数当做普通函数来执行,同时改变this 指向
    Parent.call(this)
  }

  Child.prototype = Object.create(Parent.prototype)

  // 注意:定义子类原型方法要在改变原型指向之后再定义
  Child.prototype.ability = ()=>{
    return "有勇有谋"
  }

  let michey = new Child()
  console.log(michey.name, michey.familyName, michey.skill(), michey.ability())
  // Michael Corleone 保护家人 有勇有谋

父类公有属性和方法为子类公有属性和方法,父类私有属性和方法为子类私有属性和方法

2. ES6类继承

  class Parent{
    constructor(name, generation){
      this.name = name
      this.generation = generation
    }
    info(){
      return `${this.name} Corleone,是第${this.generation}代教父`
    }
  }

  class Child extends Parent{
    constructor(name, generation, end){
      super(name, generation)
      this.end = end
    }
    skill(){
      return "除暴安良"
    }
  }

  let vito = new Child('Vito', 1, '黑')
  let michey = new Child('Michael', 2, '白')
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 今天感恩节哎,感谢一直在我身边的亲朋好友。感恩相遇!感恩不离不弃。 中午开了第一次的党会,身份的转变要...
    迷月闪星情阅读 10,620评论 0 11
  • 彩排完,天已黑
    刘凯书法阅读 4,331评论 1 3
  • 没事就多看看书,因为腹有诗书气自华,读书万卷始通神。没事就多出去旅游,别因为没钱而找借口,因为只要你省吃俭用,来...
    向阳之心阅读 4,829评论 3 11
  • 表情是什么,我认为表情就是表现出来的情绪。表情可以传达很多信息。高兴了当然就笑了,难过就哭了。两者是相互影响密不可...
    Persistenc_6aea阅读 126,220评论 2 7