一、 定义类
class People {constructor (name, age) {this.name = namethis.age = age}showName () {console.log(this.name)}
}
let p1 = new People('xiaoxiao', 30)
console.log(p1)
// People {name: 'xiaoxiao', age: 30}
小节:
- 使用class关键字声明类
- 使用constructor 构造器声明动态属性
- 在类的第一层级声明动态方法
二、 继承类的动态属性和方法
class People {constructor (name, age) {this.name = namethis.age = age}showName () {console.log(this.name)}
}
let p1 = new People('xiaoxiao', 30)
console.log(p1)
// People {name: 'xiaoxiao', age: 30}class Coder extends People {constructor (name, age, company) {super(name, age) // 继承属性this.company = company // 当前类自有属性}showCompany () {console.log(this.company)}
}
let c1 = new Coder('xiaoxiao', 18, '小米')
console.log(c1)
c1.showName()
c1.showCompany()
小节:
继承类的声明: class + 子类名 + extends + 父类名
动态属性接收继承:construtor + super (需要被继承的属性)
动态方法的继承: 根据子类继承父类自动继承
子类调用父类的动态方法: 实例. 方法名
三、顶层属性设置与获取
class People {constructor (name, age){this.name = namethis.age = agethis._sex = -1 // 0 : 男, 1: 女}get sex () {if (this._sex === 0) {return '男'} else if (this._sex === 1) {return '女'} else {return 'error'}}set sex (value) {if (value === 0 || value === 1) {this._sex = value}}
}
let p1 = new People ('xiaoxiao', 18)
p1.sex = 1
console.log(p1.sex)class Coder extends People {constructor (name, age, company) {super(name, age) // 继承属性this.company = company // 当前类自有属性}showCompany () {console.log(this.company)}
}
let c1 = new Coder('张三',20, '腾讯')
c1.sex = 0
console.log(c1.sex)
小节:
- 顶层属性通过 中间值声明变量、设置变量、获取变量来实现
- 顶层属性和构造函数的属性区别在于,顶层属性可以处理业务逻辑,并在类里面的第一层; 构造函数属性无法处理业务逻辑,并在构造器里面的第一层
- 顶层属性会自动被子类继承,构造函数的属性,需要手动使用super 关键字接收继承
四、静态方法和静态属性
1.静态方法
class People {constuctor (name, age) {this.name = namethis.age = age}static say () {return '你好'}
}
let p1 = new People ('xiaoxiao', 18)
console.log(People.say())
// 你好
class Coder extends People {constructor (name, age, company) {super(name, age) // 继承属性this.company = company // 当前类自有属性}showCompany () {console.log(this.company)}
}
console.log(Coder.say())
// 你好
小节:
静态方法声明:再类第一个层级使用static关键字声明
静态方法调用:使用类名.方法名 调用
子类自动继承父类的静态方法,使用子类名.方法名调用
2. 静态属性
class People {constuctor (name, age) {this.name = namethis.age = age}
}
People.count = 1
console.log('父类静态属性', People.count)
class Coder extends People {constructor (name, age, company) {super(name, age) // 继承属性this.company = company // 当前类自有属性}showCompany () {console.log(this.company)}
}
console.log('子类继承父类的静态属性', Coder.count)
小节:
静态属性声明:类名.属性名 = 值
静态属性调用: 类名.属性名
子类继承父类: class 子类名 extends 父类名
子类调用继承静态属性: 子类.属性名