Javascript getters and setters - recursion issue

前端 未结 2 1277
不知归路
不知归路 2020-12-06 12:12

Can someone please help me understand the significance of the \'_\' character in the setters and getters of javascript. For example I have the following code which works fi

相关标签:
2条回答
  • 2020-12-06 13:07

    It'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.

    0 讨论(0)
  • 2020-12-06 13:11

    It's naming convention used to identify private variables or properties. The _ has no sign particular significance to JS.

    From Airbnb JavaScript style guide:

    Use a leading underscore _ when naming private properties.

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

    0 讨论(0)
提交回复
热议问题