Hi There. Can someone explain to me how getters and setters in JS OOP work? As far as I understood, it’s for protecting the code inside the object. When it comes to protection, the setter method comes in very handy, so you can write a conditional inside it that will prevent updating object properties from outside the object depending on the condition you set. What is the purpose of a getter? I have been struggling to understand this concept very well. Can we live without the getter method and yet have a functional setter, or do we usually need both?
It’s a style or paradigm of writing code (object-oriented).
In the wild you’re more likely to see OOP with regards to C++, Java, and C#, maybe less so in JS these days. It’s still useful to know what the principles are and in which cases they might be useful:
Also a small note, you don’t return the constructor properties as much as you return the given instance’s properties. So for example if you have a class Person and you instantiate an instance of Person
joe = new Person("Joe");
joe is considered that one instance.
If you make a new instance, it will not know anything about other instances
mary = new Person("Mary");
mary.getName(); // returns Marys name, not joe's