Objects have properties and methods. Properties are a way to describe the state the object is in, methods are ways to change that state and to let the object "behave":
class Person {
constructor(name){
this.name = name; //name is a property
}
//And here weve got a method:
sayHi(){
alert(`Hi, im ${this.name}!`);
}
}
However while in most cases its very clear to seperate "state" and "behaviour" ( aka properties and methods) sometimes it is not. Lets imagine the person has a label sign method:
showLabel(){
document.body.innerHTML = this.name;
}
Now we change the persons name e.g.:
const person = new Person("Jake");
person.showLabel();
person.name = "Jack";
However, the label wont update :/, so while we renamed Jake to Jack, his label still shows Jake. Thats bad. For that, getters and setters were invented. These are methods that have the main aim to get and set a property (surprise ;)), but they also prevent glitches like the above one and they have many advantages, thats why they are used excessively in other languages. A sample setter for Person would be:
setName(name){
//Set
this.name = name;
//Prevent glitches
this.showLabel();
}
So instead of setting person.name
directly, we now call the setter person.setName("Jack")
. However now weve got an inconsistency between properties and properties one should not set but use a setter instead. To solve that inconsistency, js introduced get
and set
. Internally it behaves like methods, externally it still looks like a simple property:
get name(){ return this._name }
set name(value){
this._name = value;
this.showLabel();
}
Usable as:
const person = new Person("Jake");
person.showLabel();
person.name = "Jack"; //let the magic happen ;)
TLDR: get
& set
are basically a mixin of properties and methods to combine the advantages of both and to allow consistency.