class Person {
#name;
constructor(name) {
this.#name = name;
}
introduce() {
console.log(`Hello, my name is ${this.#name}.`);
}
}
class Student extends Person {
#grade;
constructor(name, grade) {
super(name);
this.#grade = grade;
}
introduce() {
console.log(
`Hello, my name is ${this.#name} and I am in grade ${this.#grade}.`
);
}
}
const student = new Student("John", 5);
student.introduce();
Private fields are not inherited by subclasses. The #name field is not accessible in the Student class, so the introduce method will throw an error. To fix this, you can add a getter method to the Person class that returns the value of the #name field.
class Person {
#name;
constructor(name) {
this.#name = name;
}
introduce() {
console.log(`Hello, my name is ${this.#name}.`);
}
_getName() {
return this.#name;
}
}
class Student extends Person {
#grade;
constructor(name, grade) {
super(name);
this.#grade = grade;
}
introduce() {
console.log(
`Hello, my name is ${this._getName()} and I am in grade ${this.#grade}.`
);
}
}
const student = new Student("John", 5);
student.introduce();