I am trying to understand how and why to use getters and setters, and private fields in general. I have read lots of explanations and none of them make sense to me. My understanding is that we do this to protect the field from manipulation. However, if the field holds an object of any type, it is still mutable and therefore manipulatable.
For example,
class Object2 {
#jaxx = 'cat'
constructor(){}
}
const object1 = {jaxx: 'cat'}
const Object2 = new Object2()
object1.jaxx = 'dog'
console.log('object1.jaxx', object1.jaxx)
console.log('object2.getJaxx', object2.getJaxx)
playField.getJaxx = 'dog'
console.log('object2.getJaxx', object2.getJaxx)
Console:
object1.jaxx dog
object2.getJaxx ƒ getJaxx(){
return this.#jaxx
}
object2.getJaxx dog
I wrote a class called EasyAccessorJS but I am hesitant to use it without understanding what is going on.
So then — what is the point? There must be a reason for this. I have read many, many explanation but none of them make sense to me.
I tried setting private field to prevent the manipulation of the field.