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()
复制代码

转载于:https://juejin.im/post/5c7f245c6fb9a049d81c99fb

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值