There is such code:

class Ab{ constructor(n){ this.name = n; } get name(){return this._name } set name(value){ this._name = value } } console.log(new Ab(1).name); 

Everything is working. The question is this. If you put _ in the setter or getter before the name of the method / property, what will the interpreter do? That is, in fact there is no such property, but it takes this property, but without _

    1 answer 1

    If you put _ in the setter or getter before the name of the method / property, what will the interpreter do?

    Nothing will do.

    In this case, the following javascript feature is used: creating a field in its absence at the time of assignment.

    The first time this._name assigned, an appropriate field is created in the object.

    As a result, the record of this class is equivalent to the following:

     class Ab{ constructor(n){ this._name = n; } get name(){return this._name } set name(value){ this._name = value } } 

    The behavior has not changed in any way, but now it is clear that the get and set methods simply use the existing field, which is initialized in the constructor.


     class Ab { constructor(n) { this.name = n; } get name() { return this.$name } set name(value) { this.$name = value } } console.log(new Ab(1).name); class Ab1 { constructor(n) { this.name = n; } get name() { return this.custom } set name(value) { this.custom = value } } console.log(new Ab1(2).name); 

    • I didn’t understand the etit from this explanation. Duck I get right with my answer or not? - Diskyp
    • @Diskyp, no. no matter which field name will be used inside the property, the important thing is that in the constructor at the moment of assignment it is created and then used. - Grundy
    • And what do you call a property in this situation? I can only find the field here, the methods: where one is the getter, and the other is the setter, the class and the constructor. - Diskyp
    • @Diskyp, by analogy with C #, is a set of get / set . Although from the point of view of js any field / method is a property and you can get it PropertyDescriptor - Grundy
    • And "no matter what the name of the field," implied "no matter how many underscores"? Cause if the TC in the getter would have specified this.$name , for example, then it would give it undefined instead of one. And if this._n____a_m___e , then nothing would have changed. - Diskyp