Hello everyone, I’m on the “Build a library” portion of Javascript Syntax 3 where we are learning about classes. My question is mostly about when to use the _variableName inside of a method versus using the getter or setter method instead. For example, I’ve created a setter method for a boolean isCheckedOut
set isCheckedOut(bool) {
this._isCheckedOut = bool
}
next, we need to create a ToggleCheckoutStatus method that flips the property value.
Initially, I assume I want to call the setter method for isCheckedOut like this:
this.isCheckedOut(!this._isCheckedOut) // call the setter method this.isCheckedOut passing in the negated property value
this should flip my this._isCheckedOut boolean value.
However, the tip says to instead do this:
this._isCheckedOut = !this._isCheckedOut
which seems much more simple I must say. However, I thought it was bad practice to access properties this way and change them directly no? When is it ok to do this? Would my first version even work?
Something we have to contend with when writing a setter is the parameter. There must be one, and only one parameter. One way of approaching this is to simply assign the parameter to the property, and all is done.
What about when we don’t want a parameter (such as toggle state)? JS makes it easy for us, just don’t use the parameter. Mind, a linter will squawk over the unused variable. We seem to be bound by the core syntax, in essence, albeit we can manipulate and validate and dress up the value being set.
A compromise is to use a helper method to do the toggling.
My understanding is that accessing the getter instead of the property itself (i.e., with the underscore) is best because the getter might (in advanced circumstances) have other pieces of code (such as error treatment) that would be appreciated when using our method.
Hence, I wanted to use this thread and ask for confirmation regarding this understanding and ask for any documentation that might help me with this topic since I am still somewhat confused.
Beyond that, I have some feedback: the “hints” for tasks 7 and 8 (method creation) also do not include an underscore, but the hint for task 6 (another method creation) does… I understand not diving into this topic at a hint, but consistency would be appreciated.