ES6类的继承

  • es6的类
class Person {
  constructor(name, age){
    this.name=name;
    this.age=age;
  }
  // 原型成员 
  // 只能有person的实例来访问
  sayHello(){
    console.log(this.name+ 'hello')
  }
  // 静态成员
  // 只能有类自己来访问
  static haha() {
    console.log('sss')
  }
}
var p1=new Person('张三', 18)
p1.sayHello()
Person.haha()
复制代码
  • 以前类的写法
function Person(name, age) {
  this.name = name
  this.age = age
}

Person.prototype.sayHello = function () {
  console.log(this.name)
}

var p1 = new Person('张三', 18)

p1.sayHello()
复制代码
  • es6类的继承
class Person {
  constructor(name, age){
    this.name=name;
    this.age=age;
  }
  sayHello(){
    console.log(this.name+ 'hello')
  }
  static haha() {
    console.log('sss')
  }
}

// 定义了一个名字叫Student的类, 继承自Person
class Student extends Person {
  // 当子类没有本身的构造函数的时候默认调用父类的构造函数来初始化子类成员
  // 当子类没有了本身的构造函数以后 那么 new Student 就调用本身的构造函数
  // 当子类拥有了本身的构造函数以后,就必须在构造函数中手动调用父类构造函数,把实例成员初始化到子类内部
  // 调用 super 必须在构造函数的第一行调用
  constructor(name, age, stuId) {
    // 构造函数中的super 是一个固定的方法,用来指代当前类的父类构造函数
    super(name, age)
    this.stuId = stuId
    console.log('子类')
  }
  study () {
    console.log('我是子类')
  }
}
const s1=new Student('张三', 18, 123)
s1.study()
s1.sayHello()

class Teacher extends Person {
  constructor(name, age, salary) {
    super(name, age)
    this.salary= salary
  }
  teaching() {
    console.log('teaching')
  }
}

const t1=new Teacher('zzz',19, 100)
t1.sayHello()
复制代码
相关文章
相关标签/搜索