I am reading about Object oriented programming and i am at a loss why i should use getters and setters instead of just regular functions.
take this code for example
class Stack {
constructor(){
this.stack = []
}
...
get lengthWithSetter(){
console.log('length')
}
lengthWithFunction(){
console.log('length')
}
}
const newStack = new Stack()
to call the lengthWithSetter method (accessor)
i can call it like this
newStack.lengthWithSetter
while calling the lengthWithFunction method while calling the lengthWithSetter with
newStack.lengthWithFunction()
my question is since newStack.lengthWithFunction() is consistent and has the structure of calling a normal function, while then do we have getters and setters.
because reading a code with getters and setters make it seem like they are properties and not methods (don't slander me for this).
So please can someone help answer this question, why do we need getters and setters when we can use regular functions
Top comments (0)