類聲明與構(gòu)造函數(shù)
class 聲明類
constructor 構(gòu)造函數(shù)
<script>
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
//方法
showPerson() {
console.log(this.name, this.age);
}
}
//實例化
let person = new Person("番茄向前看", "18");
person.showPerson();//調(diào)用類方法
</script>
繼承與超類
<script>
//定義父類
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
//方法
showPerson() {
console.log(this.name, this.age);
}
}
//子類的繼承
class Worker extends Person {
constructor(name, age, job) {
super(name, age);//可以使用super(超類)繼承屬性
this.job = job;
}
//方法
showJob() {
console.log(this.job);
}
}
//實例化子類
let workers = new Worker("石頭", "15", "沒有工作")
//調(diào)用子類方法
workers.showJob()
//調(diào)用父類方法
workers.showPerson()
</script>