类和继承
类
javascript
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHello() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
const person1 = new Person('John', 25);
person1.sayHello(); // 输出 "Hello, my name is John and I am 25 years old."继承
javascript
class Student extends Person {
constructor(name, age, major) {
super(name, age);
this.major = major;
}
sayHello() {
console.log(`Hello, my name is ${this.name} and I am a ${this.major} student.`);
}
}
const student1 = new Student('Jane', 20, 'Computer Science');
student1.sayHello(); // 输出 "Hello, my name is Jane and I am a Computer Science student."