What are your thoughts on using getters & setters in Javascript as opposed to methods? And when and why would you use them?
This
const obj1 = {
_name: 'Rick',
get name(){
return this._name;
},
set name(name){
this.name = name;
}
};
As opposed to
const obj2 = {
_name: 'Morty',
getName() {
return this._name;
},
setName(name){
this.name = name;
}
};
Top comments (5)
I've had trouble with
tsc
(TypeScript compiler)'sget
andset
in the past, as well as I don't see much benefit.Also the same case with Python, I see
get
andset
as generally should be avoided, as they may obscure implementation.The only real time I see benefit, is in Vue class components, where
get
will be translated to Vue getters, therefore cached.I tend to forget about them and don't use them often, can't see why. I was hoping somebody explained how they used them and why.
I don't use getters/setters often, but sometimes they make interfaces look a lot cleaner, for example:
myArray.length
instead ofmyArray.length()
I really don’t use them. Mostly because I keep forgetting they exist.
Is there any performance reason to not use them?
I also forget about them :P
I don't think there is, although I haven't made much research in that respect.
Correction: It kinda has some side-effects and is prone to errors, for example, if a method or property is mispeled: