1.ES5中类和继承
2.ES6中类和继承
class People {
constructor(name, age) {
this.name = name
this.age = age
this._sex = -1
}
get sex() {
if (this._sex === 1) {
return 'male'
} else if (this._sex === 0) {
return 'female'
} else {
return 'error'
}
}
set sex(val) {
if (val === 1 || val === 0) {
this._sex = val
} else {
this._sex = -1
}
}
showName() {
console.log(this.name)
}
//静态方法
static getCount() {
return 3
}
}
let p1 = new People('qqq', 12)
console.log(p1)
p1.sex = 1
console.log(p1.sex)
p1.sex = 0
console.log(p1.sex)
p1.sex = 7
console.log(p1.sex)
//静态方法调用
console.log(People.getCount())
//静态属性
People.number = 999
console.log(People.number)
class Coder extends People {
constructor(name, age, company) {
super(name, age)
this.company = company
}
showComany() {
console.log(this.company)
}
}
let c1 = new Coder('www', 23, 'ddd')
console.log(c1)
c1.sex = 1
console.log(c1.sex)
//静态方法调用
console.log(Coder.getCount())
结果