Can somebody please tell me about getters and setters in javascript? What are actually getters and setters? Where we can use them? What are the benefits of using them?
3 Answers
Generally, getters and setters are used for Object Oriented Programming in Javascript.
Typically, in a class, there are some attributes, a constructor, getters and setters.
Attributes represent properties of a class
Constructor creates an instance of a class
Getters help to retrieve the attributes of an object
var name = cat.getName();
Setters help to manipulate the attributes of an object.
eg. cat.setName('Kathreen');
Read more about OOP in Javascript to find out more.
- 1,784
- 3
- 29
- 40
You might use a getter or setter if you want to put conditions on the setting/getting of a property value, or have something else happen when they are set/got.
You may also find the MDN documentation on the Mozilla proprietary set and get operators helpful:
- 134,457
- 30
- 163
- 204
Getter and setter both are functions.
Getter will call when a value is retrieve from variable/object(which has Getter) Getter function must return value.
var i=count;
if the count's getter is already defined, it will call.
Setter will call when a value is assign to a variable/object(which has Setter)
count=10
if the count's setter is already defined, it will call.
take a look at this example so that you can easily understand the use of Getter and setter
How to get notified within an object when one of that object’s property changes?
- 4,109
- 7
- 27
- 51