(emphasis mine)
As far as I understood previous readings, writing getters and setters does nothing to stop access to the object’s properties, they are still directly accessible if one were to try it - correct?
- About methods that manipulate the values of properties: should they use the setter for that property or the “direct-access” syntax?
So in this example, which is preferable for eatTooManyTreats()
:
function dogFactory (weight) {
return {
_weight: weight,
get weight() {
return this._weight;
},
set weight(newWeight) {
this._weight = newWeight;
},
eatTooManyTreats() {
this._weight += 1;
}
}
}
or something like this:
function dogFactory (weight) {
return {
_weight: weight,
get weight() {
return this._weight;
},
set weight(newWeight) {
this._weight = newWeight;
},
eatTooManyTreats() {
set weight(this._weight + 1);
}
}
}
(I just realized I don’t understand how to call the setter properly…)
-
Why is there no underscore in the definition of the getter/setter when the property name actually has one? So why does JS “know” we mean the _weight
property when we write the getter like get weight()
rather than get _weight()
.
-
The usage of this
is quite confusing to me.
get weight() {
return this._weight;
},
Here we have to explicitly state that we want to return the weight
property of this
object, and not some other one - but only in the function body! We are, however, not saying:
get this._weight() {
return this._weight;
},
(granted, it looks very tautological, but so does a lot of object oriented code), so the information which object we want to know the weight property of is missing from the declaration part, but have to state it in the function body. Why, though?