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

Advertisements

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!

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

Leave a ReplyCancel reply