学习内容:
- 类的定义
- 类的继承
- 静态属性和方法的定义
ES6中,用class关键字声明一个类:
class Peple {
constructor(name,age) {
this.name = name
this.age = age
}
showName() {
console.log(this.name)
}
}
let p1 = new Peple('Sure',36)
console.log(p1)
-----------------------------
Peple {name: 'Sure', age: 36}
继承的完整例子:
class People {
constructor(name,age) {
this.name = name
this.age = age
}
showName() {
console.log(this.name)
}
}
let p1 = new People('Sure',34)
console.log(p1)
class Coder extends People {
constructor(name, age, company) {
super(name, age) // 通过super关键字定义
this.company = company
}
showCompany() {
console.log(this.company)
}
}
let c1 = new Coder('Sure',36,'Neu')
console.log(c1)
c1.showName()
c1.showCompany()
----------------------------------------------
People {name: 'Sure', age: 34}
Coder {name: 'Sure', age: 36, company: 'Neu'}
Sure
Neu
在class内部定义顶层属性是通过get/set关键字来实现:
class People {
constructor(name,age) {
this.name = name
this.age = age
this._sex = -1 // 为了不让set方法有死循环,这里需要定义新的变量
}
get sex() { // 对象里方法的简洁表示法
return this._sex
}
set sex(val) { // 如果不写set方法,那么这个属性只有get方法,是只读的
// this.sex = val // 这样写会造成死循环,设置值就会调用set,调用set又会设置值...所以要引入新的变量
this._sex = val
}
showName() {
console.log(this.name)
}
}
let p1 = new People('Sure',34)
console.log(p1)
p1.sex = 'femal'
console.log(p1.sex)
class Coder extends People {
constructor(name, age, company) {
super(name, age) // 通过super关键字定义
this.company = company
}
showCompany() {
console.log(this.company)
}
}
let c1 = new Coder('Sure',36,'Neu')
console.log(c1)
c1.showName()
c1.showCompany()
// --------------------------------------------------------
// People {name: 'Sure', age: 34, _sex: -1}
// Femal
// Coder {name: 'Sure', age: 36, _sex: -1, company: 'Neu'}
// Sure
// Neu
上面的代码会有这样的疑问,写了get/set其实和上面定义在构造里的属性没啥区别,但是为什么要写get/sex呢?其实,当在get/set时如果有业务逻辑需要处理时,get/set方法就能派上用场了。
ES6定义静态方法:
class People {
constructor(name,age) {
this.name = name
this.age = age
}
static getCount() { // ES6当中定义静态方法
return 5
}
}
let p1 = new People('Sure',34)
console.log(People.getCount())
// --------------
// 5
ES6当中定义静态属性和ES5是一样的:
class People {
constructor(name,age) {
this.name = name
this.age = age
}
static getCount() { // ES6当中定义静态方法
return 5
}
// static count = 0 // ES6中不可以这样定义静态属性
}
People.count = 6 // ES6当中定义常量和ES5一样
console.log(typeof People)
console.log(People.count)
--------------
function
6