Javascript getters and setters - recursion problem

Can someone please help me understand the meaning of "_" character in javascript setters and receivers. For example, I have the following code that works great.

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 looks like this, then my code doesn't work and I get an error in the browser console stating "RangeError: Maximum call stack size".

var user = {
    get name() {
        return this.name;
    },    
    set name(value) {
        this.name = value;
    }
};

var me = user;
me.name = "Rob";

alert(me.name);

</script>

      

Can someone explain to me what "_" does in this situation?

+3


source to share


2 answers


It's pretty simple. In your second example get

, calls itself.

Since you are referring to a property me.name

, JavaScript must get

use that property. When this happens, the getter is triggered. Using your second example, JavaScript calls the getter, but then the getter is prompted to do the same: get the property it is intended to handle. The function always calls itself, making it infinitely recursive.



However, in the first example, the property that is retrieved in the getter is not the same as the one that the getter originally called. The value returned by the getter is part of the storage component to avoid the recursion problem mentioned above. These two properties have no real connection between them, although they have similar names.

The same goes for the installer.

+6


source


This is a naming convention used to identify private variables or properties. _

doesn't really matter to JS.

From Airbnb JavaScript Style Guide :



Use the leading underscore _ when assigning personal properties.

https://github.com/airbnb/javascript#22.4

+1


source







All Articles