why I am getting a age getter in main Object it should be in prototype only
class PersonCl {
constructor(fullName, birthYear) {
this.fullName = fullName;
this.birthYear = birthYear;
}
// Instance methods
calcAge() {
console.log(2037 - this.birthYear);
}
greet() {
console.log(`Hey ${this.fullName}`);
}
get age() {
return 2037 - this.birthYear;
}
set fullName(name) {
if (name.includes(' ')) this._fullName = name;
else alert(`${name} is not a full name!`);
}
get fullName() {
return this._fullName;
}
// Static method
static hey() {
console.log('Hey there 👋');
}
}
class StudentCl extends PersonCl {
constructor(fullName, birthYear, course) {
// Always needs to happen first!
super(fullName, birthYear);
this.course = course;
}
}
const martha = new StudentCl('Matha Jones', 2012, 'Computer Science');
console.log(martha);
maybe all the getter considered as a regular properties idk (pardon my English) is it becuase of super function or inheritance ?
2
Answers
Yes, it is because of inheritance. You can make the method private to prevent it from being inherited:
The
age
getter is on the prototype, not on the main object as an own-property like the console is making you think – that’s why theage
getter property in your screenshot isn’t bold like the other properties such asbithYear
,course
and_fullYear
which are all own-properties. Since Chrome 95, it will (source):Note: The getter properties in your example also appear greyed out, which indicates that they’re non-enumerable.
Here’s another example that shows how a getter on the prototype still appears on the main object when logged, just non-bolded:
Example output in Chrome, notice how
b
is not bold, whereasa
is asa
is an own-property:If you’re unsure about if something is on the main object, the most reliable check is to use
Object.hasOwn()
, or if you can’t support thatObject.prototype.hasOwnProperty()