类声明与构造函数
class 声明类
constructor 构造函数
<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();//调用类方法
</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", "没有工作")
//调用子类方法
workers.showJob()
//调用父类方法
workers.showPerson()
</script>
网友评论