Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is it that even after a stack overflow error, in getter and setter methods, the rest of my code still works in JavaScript?

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading