js中class类用法与理解
先直接上代码:
// 父类
class Person{
// 当有必要在父类设置初始化属性时,必须使用constructor方法
constructor(name,action,time){
this.name = name
this.action = action
this.time = time
}
// 设置私有方法(仅父类可以调用)
static hobby(ho){
return ho
}
// 设置公有方法
when(){
return this.time
}
doWhat(){
return this.action
}
who(){
return this.name
}
}
// 子类(继承父类时,使用extends来继承父类)
class Father extends Person{
// 初始化子类属性及继承父类属性
constructor(name,action,time,address){
// super方法继承父类属性
super(name,action,time)
this.address = address
}
// 子类公有方法
where(){
return `在${this.address}`
}
}
// 仅父类可以调用父类的私有方法
document.getElementById('test').innerHTML = Person.hobby('reading')
console.log(Person1.hobby('reading'))
// 声明子类实例
const lai = new Father('I','study','now','home')
// 调用父类和子类的方法
console.log(lai.name,lai.where(),lai.doWhat(),lai.when())