What is the significance of the '_' character in the setters and getters of JavaScript?
For example, I have the following code which works fine.
var user = {
get name() {
return this._name;
},
set name(value) {
this._name = value;
}
};
var me = user;
me.name = "Rob";
alert(me.name);
But if I remove the underscore so my code will look like the following, then my code won't work and I get a an error in the browser console stating "RangeError: Maximum call stack size exceeded."
var user = {
get name() {
return this.name;
},
set name(value) {
this.name = value;
}
};
var me = user;
me.name = "Rob";
alert(me.name);
</script>
What does the "_" do in this situation?
What is the significance of the '_' character in the setters and getters of JavaScript?
For example, I have the following code which works fine.
var user = {
get name() {
return this._name;
},
set name(value) {
this._name = value;
}
};
var me = user;
me.name = "Rob";
alert(me.name);
But if I remove the underscore so my code will look like the following, then my code won't work and I get a an error in the browser console stating "RangeError: Maximum call stack size exceeded."
var user = {
get name() {
return this.name;
},
set name(value) {
this.name = value;
}
};
var me = user;
me.name = "Rob";
alert(me.name);
</script>
What does the "_" do in this situation?
Share Improve this question edited Sep 24, 2023 at 21:48 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked Jun 12, 2015 at 18:31 Sohrab HejaziSohrab Hejazi 1,5116 gold badges18 silver badges29 bronze badges 2 |2 Answers
Reset to default 14It's quite simple. In your second example, the get
, calls itself.
Since you reference the property me.name
, JavaScript needs to get
that property. When this happens, the getter is triggered. Using your second example, JavaScript calls the getter, but the getter is then told to do the exact same thing: get the property that it is meant to handle. The function always calls itself, making it infinitely recursive.
However, in the first example, the property that is being retrieved in the getter is not the same as the one that originally triggered the getter. The value being retreived by the getter is somewhat of a storage component to avoid the problem of recursion mentioned above. The two properties have no actual connection between them even though they have similar names.
The same idea applies to the setter.
Its naming convention used to identify private variables or properties. The _
doesn't have any sign of particular significance to JavaScript.
From the Airbnb JavaScript style guide:
Use a leading underscore _ when naming private properties.
https://github.com/airbnb/javascript#22.4
_name
(with underscore) is private to youruser
object but thename
(without underscore) is public and changeable from the outside scope. so basically, you callname
from outside, which then calls itself again and hence it becomes recursive. – Tahir Ahmed Commented Jun 12, 2015 at 18:35