Please tell me if it is the correct practice to describe the internal fields of the class (ES6) and the closure functions as follows:

class A { a = 1; print = () => { console.log(this.a); } } 

    2 answers 2

    From the point of view, and 6 , and 7 versions of the specification

    The body of the class has the following structure

     ClassBody [Yield] :  
         ClassElementList [? Yield]
    
     ClassElementList [Yield] :
         ClassElement [? Yield]
         ClassElementList [? Yield] ClassElement [? Yield]
    
     ClassElement [Yield] :
         MethodDefinition [? Yield]
         static MethodDefinition [? Yield]
         ;
    

    In turn, MethodDefinition is

     MethodDefinition [Yield] :
         PropertyName [? Yield] (StrictFormalParameters) {FunctionBody}
         GeneratorMethod [? Yield]
         get PropertyName [? Yield] () {FunctionBody}
         set PropertyName [? Yield] (PropertySetParameterList) {FunctionBody}
    

    As you can see, in the body of the class, only the definition of functions is allowed, without the use of an assignment operator, and the code in question should cause a syntax error.

    Therefore, the question

    is the proper practice of describing the internal fields of a class (ES6)

    You can definitely answer: no , from the point of view of the specification - this code should not even be executed.

    On the other hand, from the point of view, for example, of TypeScript, such declarations are quite a place to be.

      At the moment I do not know that the specification supports the declaration of properties in the body of the class. But I heard that this will be in the next versions, but for now this feature can be implemented using babel .

      Is this correct? Yes it is! The compiler collects these properties for you and writes them into the constructor. Therefore, if it is more convenient for you to read the code, then write.

      Just want to say a few words about get/set mentioned earlier .. Accessors should be used only in cases where they do not return an object by direct link. That is, if you have the property this._object and you want to return it through the getter get object() { return this._object; } get object() { return this._object; } , then it will be immoral and meaningless (unless you certainly want to call something when changing), since the essence of the getters is to restrict access to the object, but in this case you give the object completely and anyone can do anything with it. The accessors target around this get object() { return this._object.props; } get object() { return this._object.props; } .