Class Features Have Landed!

The three big class proposals advanced to Stage 4 ("Finished") on the 19th! That means they have multiple implementations in the wild (though possibly still behind flags in some cases). The proposals are:

Huge congrats and thanks to Dan Ehrenberg, Kevin Gibbons, and everyone else who worked on the proposals — these were hard to get right, and IMHO they did.

Huge thanks to the hard-working people who implemented these in JavaScript engines! (I'd like to name names, but I don't know them, so I've asked on Twitter — see the shout-outs there!)

All of the above are shipping unflagged in Chromium-based browsers and Node.js v14 or later thanks to the V8 team. Support for some of them is in Firefox and Safari and more is coming soon thanks to the folks working on SpiderMonkey and JavaScriptCore.

Here's a silly class (that shows my age) showing all of the features from those proposals:

class Guide {
    // Public instance field definition
    answer = 42;

    // Private instance field declaration
    #question = "Life, the Universe, and Everything";

    // Private instance method
    #quoteDeepThought() {
        console.log(`[Deep Thought]: ${this.#question}. There is an answer. But, I'll have to think about it.`);
    }

    // Private accessor (you can just a getter, or just a setter, if you want)
    get #flyingAttempts() {
        return /*...get the value from wherever it's stored...*/;
    }
    set #flyingAttempts(attempts) {
        /* ...store the value wherever it gets stored... */
        console.log(`#flyingAttempts set to ${attempts}`);
    }

    // A private static field
    static #author = "Douglas Adams";

    // A private static method
    static #makeFjords() {
        console.log(`[Slartibartfast]: "My idea, when we started out, was to have sort of an undulating..."`);
    }

    // A public method using some of those
    example() {
        this.#quoteDeepThought();
        console.log(`(Seven and a half billion years later, the answer was: ${this.answer}.)`);
        Guide.#makeFjords();
        console.log(`Author: ${Guide.#author}`);
    }
}

(I go into the details of all of the features in Chapter 18 of the book.)

Happy coding!

Have a question or comment about this post? Ping me on Mastodon at @tjcrowdertech@hachyderm.io!