Class fields and methods

Fields

Class fields are declared directly within the body of a class, not explicitly added as a property of the this value. However, the result is the same: a property defined on instances of that class.

class MyClass {
    myField;
}

const myClassInstance = new MyClass();

myClassInstance;
> MyClass { myField: undefined }

You can initialize a field with a value. This is often a default value that logic within the class can overwrite:

class MyClass {
    myResult = false;
    set setValue( myValue ) {
        this.myResult = myValue;
    }
}
const myClassInstance = new MyClass();

myClassInstance;
> Object { myResult: false }

myClassInstance.setValue = true;

myClassInstance;\
> Object { myResult: true }

Class fields are functionally identical to properties attached to the class using this. This means they can be accessed and modified from outside the class like any other property.

class MyClass {
    myField = true;
}

const myClassInstance = new MyClass();

myClassInstance.myField;
> true

myClassInstance.myField = false;

myClassInstance.myField;
> false;

Fields provide a basis for some of the more advanced features of classes.

Private fields and methods

Private fields and methods are inaccessible outside a class. A private property is associated with an instance of a class, meaning that each instance contains its own set of private fields and methods, as defined on the class.

To make a property private, add a # to the beginning of the identifier when you declare it:

class MyClass {
    #myPrivateField = true;
    #myPrivateMethod() {}
}
const myClassInstance = new MyClass();

myClassInstance;
> MyClass { #myPrivateField: true }
    #myPrivateField: true
    <prototype>: Object {  }
        constructor: class MyClass {}
        <prototype>: Object {  }

A private field must be declared in the body of the containing class. You can alter its value later as a property of this, but you can't create the field using this.

Private fields can't be accessed from elsewhere in a script. This prevents data properties from being altered outside of the getter and setter methods provided to interact with the values they contain, and it prevents direct access to methods intended only for use within the class itself.

class MyClass {
    #myResult = false;
    set setValue( myValue ) {
        this.#myResult = myValue;
    }
}
const myClassInstance = new MyClass();

myClassInstance;
> MyClass