Hi There. I have some questions about the use of underlines in this Getters and Setters tutorial. I’ve Googled around to understand why one would use a _ at the beginning of a variable in JS and I find chatter about the underline being an indicator of a private variable. I think in this instance you are using it for a different reason maybe? Using the Shout Generator section as a basis for these questions, I see you create a _message property and create a setter named ‘set message’. If I throw out putting a _ in the message property, then the this.message = value.toUpperCase(); creates strange behavior (like recursive). If I leave it in, I see later when I issue shout.message = “This is sparta!”; that the setter is called. So, we are somewhat hiding the implementation of the setter, right? We are not directly setting _message, but secretly calling the setter? Also, the setter doesn’t necessarily have to have the same name as the property it sets as in the zorb example, right? I’m trying to understand the sudden appearance of the underline before the property name in this section.
I’ve Googled around to understand why one would use a _ at the beginning of a variable in JS and I find chatter about the underline being an indicator of a private variable. I think in this instance you are using it for a different reason maybe?
It’s related to the explanations you’ve found. Kirupa’s creating some backing storage for the getters and setters, but it’s an implementation detail, so it doesn’t need to be public.
Something subtle between the zorb example and the shout example is that in the zorb example, the backing property is named message, but the getters and setters are called greeting. By contrast, in the shout example, the backing property is _message and the getters and setters are message. When you take out the leading _, you’re creating a naming conflict so that the set message setter calls itself in its own definition, leading to the recursive behavior you described.
The part that’s hidden is the name (and storage) of the _message property. The public interface is the accessors (getters and setters) that don’t start with _. So you’re not hiding the fact that you’re calling the setter, you’re hiding what the setter is doing in its implementation.
Right; it’s almost always going to be a bug if it does.
I think the main problem is that Kirupa swapped from message+greeting to _message+message without explaining the rationale.
Hi Kirupa, maybe it was due to a cookie or something similar, but just to be completely sure, I tried using another browser, and the Youtube video in the Getter and Setter article did not display the correct video. It’s likely a bug on my end!
By the way, the visuals and explanation are really great!