微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ES6继承与ES5继承

https://www.jianshu.com/p/342966fdf816/
ES5继承:

ES6继承:

解决代码的复用
使用extends关键字实现继承
子类可以继承父类中所有的方法属性
子类只能继承一个父类(单继承),一个父类可以有多个子类
子类的构造方法中必须有super()来指定调用父类的构造方法,并且位于子类构造方法中的第一行
子类中如果有与父类相同的方法属性,将会优先使用子类的(覆盖)

ES6继承eg

class People {
  //父类构造方法
  constructor() {
      this.a = 100; //父类中定义的变量
      console.log("People constructor");
  }
    //原型方法
  eat() {
    console.log("eat...")
  }
    //静态方法
  static play() {
    console.log("play...")
  }
}
class Student extends People {
  //子类构造方法
    constructor() {
      super(); //调用父类构造器,必须存在,且位于子类构造器第一行的位置
      this.b = 200; //子类定义的变量
      console.log("Student constructor");
    }
    study() {
        console.log("study...");
    }
}

let stu = new Student();
console.log(stu.a, stu.b);
stu.eat();
stu.study();
Student.play();入代码

ES5继承eg

//原型链: Child -> new Parent() -> new GrandParent() -> new Object();
function GrandParent() {
  this.name = 'GrandParent';
  this.a = 3;
}
Parent.prototype = new GrandParent();
function Parent() {
  this.name = 'parent';
  this.b = 2;
}
Child.prototype = new Parent();
function Child() {
  this.name = 'child';
  this.c = 1;
}
var child = new Child();
console.log(child); // Child {name: "child", c: 1}
console.log(child.a); // 3
console.log(child.b); //2
console.log(child.c); //1

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐