一、es6中的类和继承
1. 类的定义和继承,关键字class、extends、constructor、super
class People {
constructor(name, age) {
this.name = name
this.age = age
}
showName() {
console.log(this.name);
}
}
let p = new People('zhangsan', 18)
console.log(p)
class Coder extends People {
constructor(name, age, company) {
super(name, age)
this.company = company
}
showCompany(){
console.log(this.company)
}
}
let c = new Coder('lisi', 38, 'alibaba')
c.showName()
c.showCompany()
2. 定义属性,这边注意设置死循环。【set/get】
class People {
constructor(name, age) {
this.name = name
this.age = age
this._sex = -1
}
get sex() {
return this._sex
}
set sex(val){
this._sex = val
}
showName() {
console.log(this.name);
}
}
let p = new People('zhangsan', 18)
console.log(p)
class Coder extends People {
constructor(name, age, company) {
super(name, age)
this.company = company
}
showCompany(){
console.log(this.company)
}
}
let c = new Coder('lisi', 38, 'alibaba')
c.sex = '0'
console.log(c.sex)
3. 静态方法【static】
class People {
constructor(name, age) {
this.name = name
this.age = age
this._sex = -1
}
get sex() {
return this._sex
}
set sex(val){
this._sex = val
}
static getCount() {
return 5
}
showName() {
console.log(this.name);
}
}
console.log(People.getCount())
4. 静态属性的问题
People.count = 1