Categories
Featured Development Resources HTML/Javascript

JavaScript ES 2022 Object-Oriented Programming Enhancements

With ES6 the Class statement was added to JavaScript greatly improving the syntax for object-oriented programming (OOP).

ES2022 builds on this adding a number of features.

Private Fields

The most important addition related to Object -Oriented programming with ES2022 is that there is finally a way to make private fields and methods in your classes..

The syntax create these private variables is a hashtag (#) placing it before the field name will make the field private like in this example:

class ClassES2022 {
    #field

    constructor() {
        this.#field = "I'm private"
    }

    printField() {
        console.log(this.#field)
    }
}

const obj = new ClassES2022()
obj.printField()
// I'm private
console.log(obj.field)
// undefined
console.log(obj.#field) 
// SyntaxError

Also note that these fields are declared outside of a method, not within the constructor.

Private Methods

Similarly you can use the # to make a method private.

class ClassES2022 {
    static intro = "I'm static"

    constructor() {
        this.#field = "I'm private";
    }

    #printField() {
        console.log(this.#field)
    }
}

const obj = new ClassES2022();
obj.printField()
// Syntax error

Static Fields

Static fields have been added, and are declared with the static keyword at the top of the class.

class ClassES2022 {
    static intro = "I'm static"
}
console.log(ClassES2022.intro)
// I'm static
const obj = new ClassES2022();
console.log(obj.intro)
// undefined

Static Initialization Blocks

Another addition is that static initialization block which is run when the class is loaded into memory.

class ClassES2022 {
    static {
        console.log("I'm static")
    }
}
// I'm static

Public Fields

Public fields are declared at the top of your class with just the field name.

class ClassES2022 {
    intro = "I'm public"
}
obj = new ClassES2022()
console.log(obj.intro)
// I'm public

Conclusion

The additions for OO programming in ES 2022 finally allow for the implementation of object-oriented programming patterns in JS without the need for any “hacky” code like extra throw statements and pretending fields are private.

JavaScript has really come a long way.