ES6 Classes vs. Prototypes: Just Syntactic Sugar?
One of the biggest innovations in the ES6 (ECMAScript 6) standard released in 2015 was the introduction of the class keyword. Many thought that JavaScript had completely changed, but in reality, this is merely "syntactic sugar" over the existing prototype-based mechanics.
The introduction of classes provides a much cleaner, more readable structure that is more familiar to developers coming from other languages. Let's see how the prototype example from the previous article looks as a modern ES6 class:
class Developer {
constructor(name, language) {
this.name = name;
this.language = language;
}
introduce() {
return `Hi, my name is ${this.name} and I code in ${this.language}.`;
}
}
Private Methods and Fields in Classes
Modern JavaScript (ES2022+) also supports true private class members. To do this, a # (hash) character must be placed before the variable or method name. These members cannot be accessed or modified from outside the class in any way:
class BankBranch {
#balance = 0; // Private field
constructor(owner, initialAmount) {
this.owner = owner;
this.#balance = initialAmount;
}
getBalance() {
return this.#balance; // Accessible within the class
}
}