Reputation: 452
I'm working with the new Class Public Field Declarations available in Chrome 72 and I came across this genuinely strange behavior:
class Extended {
property = 5;
}
class Extending extends Extended {
get property() {
return false;
}
}
const extending = new Extending();
console.log(extending.property);
//logs 5
I would be surprised if this is the expected result since it renders the get
ter on the extending class inaccessible. Is this a bug?
Upvotes: 3
Views: 346
Reputation: 86
The getter is called. When you call extending.property first the Extending class will be checked for property, if nothing is found there then it will search for property in the Extended class, once it was found it will log the value of the property.
let's examine 2 other code snippets:
1.
class Extended {
}
class Extending extends Extended {
get property() {
return false;
}
}
const extending = new Extending();
console.log(extending.property);
//logs false
This code will print to the console false, since property can't be found in the Extending class nor in the Extended class, then the getter will return the false statement.
2.
class Extended {
property = 5;
}
class Extending extends Extended {
property = 6;
get property() {
return false;
}
}
const extending = new Extending();
console.log(extending.property);
//logs 6
This will print 6 to the console since property was found in Extending class, it won't keep checking for it in the Extended class
Upvotes: 2