I’m currently learning about setters and getters in Javascript but I ran into an issue. I’ve named a property in my class the same name as my get and set methods which I understand can lead to recursion and cause a stack overflow but why is it that ‘msg’ still gets assigned to ‘Sandra’ even after the stack overflow error?
class ClassWithGetSet{
msg = 'Hello';
get msg(){
return this.msg;
}
set msg(x){
this.msg = `Hello ${x}`;
}
}
const instance = new ClassWithGetSet();
console.log(instance.msg);
instance.msg = 'Sandra';
console.log(instance.msg);
I expected an error to output on the Chrome DevTools console but instead it printed ‘Hello’ and then’Sandra’. Your help is greatly appreciated!
2
Answers
You should not name your field and getter the same name, otherwise it will be overwritten. Consider naming the
msg
feild to something else or using a private field:From MDN :
Thus, when looking up the property, it finds the instance’s before the getter/setter pair. You’re never reaching them.