The above is completely transient and does not create anything sustainable. One would expect to see,
const joe = dogFactory('Joe', 'Pug', 27)
joe.eatTooManyTreats()
console.log(joe.weight)
Please post your entire body of code so we can test your implementation. One still contends that the method above (eatsTooManyTreats()) should not return anything. It is updating the property through the setter.
To repeat, if we have a getter/setter, then we should devote all getting and setting to those special methods.
Before we go too far, please post a link to this exercise so we can access the narrative and instructions (and review our own code).
In the meantime, I’ve reconsidered how we would use the setter in the treats method:
const dogFactory = function (name, breed, weight) {
return {
_name: name,
_breed: breed,
_weight: weight,
get weight () {
return this._weight
},
set weight (w) {
this._weight = w
},
eatsTooManyTreats () {
weight = this.weight // retrieve with getter
this.weight = weight + 1 // adjust with setter
}
}
}
> joe = dogFactory('Joe', 'Pug', 27)
> joe.eatsTooManyTreats();
> console.log(joe.weight);
<- 28
Aside
Increment and decrement operators have a prefix and a postfix state change. If in the above we were to write,
this.weight = weight++
it would have no effect since the incrementing happens after the assignment so we’ve just given weight
back in its present state.
this.weight = ++weight
will has the desired effect. The state change occurs before assignment. Try it each way and see the difference in behaviors.
> a = 5
<- 5
> a++
<- 5
> ++a
<- 7
Notice that a
did get incremented in both commands, but only echoed its correct value when prefixed. The postfix action responded with the old value.
Bottom line, we can never do too much scenario testing with whatever little code inventions we come up with, or code snippets we try to refactor. The old proviso still applies, as always: if you did not write it, don’t use it. Write and test your own code and you will be able to explain it sideways and backwards.