IKUN (坤坤)教你Class类的使用

591 阅读1分钟

类的声明

声明类那必然要用到class,不用IKUN不会答应的

// Person 为Professor 及 Student的父类(也可以叫超类)
class Person {
  constructor(name) {
    this.name = name;
  }
  introduceSelf() {
    console.log(`我是${this.name}`)
  }
}
const kk = new Person('坤坤')
kk.introduceSelf() // 我是坤坤

继承

坤坤提示: 继承关键字为extends;如果子类有任何自己的初始化内容,则必须先使用super来调用父类的构造函数,并传递父类构造函数期望的任何参数。这个例子中的参数是name

class Professor extends Person {
  constructor(name, teaches) {
    // super 调用父类的构造函数并传递name参数
    super(name)
    this.teaches = teaches;
  }
  introduceSelf() {
    console.log(`我是${this.name}, 负责你们的${this.teaches}课程`)
  }
  grade(paper) {
    const grade = Math.floor(Math.random() * 4 + 1)
    console.log(grade)
  }
}
const kk = new Professor('坤坤', '唱、跳、Rap、篮球')
kk.introduceSelf() // 我是坤坤,负责你们的唱、跳、Rap、篮球课程

封装

其实这里讲的是私有属性,关键字符为#

坤坤提示: 此例中#year为私有属性,外部不可访问,私有属性必须在类的声明中声明,并且其名称需要以#开头。私有函数同理

class Student extends Person {
  #year;
  constructor(name, year) {
    super(name)
    this.#year = year;
  }
  introduceSelf() {
    console.log(`我的名字叫${this.name},一个练习时长${this.#year}年的学生`)
  }
  canStudyArchery () {
    // 是否可以学习唱跳Rap篮球
    if(this.#year >  2.5) {
        console.log(`恭喜${this.name}同学,你可以学习唱跳Rap篮球!`)
    } else {
        console.log(`很抱歉${this.name}同学,请先回去练习两年半!`)
        this.#fn()
    }
  }
  #fn () {
    console.log('其实我已经偷偷练习了两年半,不在人前的努力是无用功吗?')
  }
}
const IKUN = new Professor('IKUN', 3)
IKUN.introduceSelf() // 我的名字叫IKUN,一个练习时长3年的学生
IKUN.canStudyArchery() // 恭喜IKUN同学,你可以学习唱跳Rap篮球!

小黑子鸡脚收起来