skip to Main Content

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


  1. 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:

    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);
    Login or Signup to reply.
  2. From MDN :

    Getter properties are defined on the prototype property of the class and are thus shared by all instances of the class.

    Thus, when looking up the property, it finds the instance’s before the getter/setter pair. You’re never reaching them.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search