class People {
constructor (name, age) {
this.name = name
this.age = age
}
showName () {
console.log(this.name)
}
}
let p1 = new People('xiaoxiao', 30)
console.log(p1)
// People {name: 'xiaoxiao', age: 30}
小节:
class People {
constructor (name, age) {
this.name = name
this.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 = name
this.age = age
this._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)
小节:
class People {
constuctor (name, age) {
this.name = name
this.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关键字声明
静态方法调用:使用类名.方法名 调用
子类自动继承父类的静态方法,使用子类名.方法名调用
class People {
constuctor (name, age) {
this.name = name
this.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 父类名
子类调用继承静态属性: 子类.属性名