总结:
1.类中的构造器不是必须要写的,要对实例进行一些初始化的操作,如添加指定属性时才写。
2.如果A类继承了B类,且A类中写了构造器,那么A类构造器中的super是必须要调用的
3.类中所定义的方法,都放在了类的原型对象上,供实例去使用
class Person {
speak() {
console.log('I can speak!')
}
}
const p1 = new Person();
p1.speak();
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
speak() {
console.log(`My name is ${this.name}, My age is ${this.age}`)
}
}
class Student extends Person {
constructor(name, age, grade) {
super(name, age);
this.grade = grade;
this.school = 'Hogwarts';
}
speak() {
console.log(`My name is ${this.name}, My age is ${this.age}`, My grade is ${this.grade})
}
}
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
class Student extends Person {
constructor(name, age, grade) {
super(name, age);
this.grade = grade;
}
school = 'Hogwarts';
study = () => {
console.log(`My name is ${this.name}`)
}
}