Classes
JavaScript offers the class syntax that's very similar to languages like Java.
class Person {
constructor(name) {
this.name = name;
}
sayHello() {
return `Hello, I'm ${this.name}!`;
}
}
const p = new Person("Maria");
console.log(p.sayHello());
JavaScript classes are just functions that must be instantiated with the new operator. Every time a class is instantiated, it returns an object containing the methods and properties that the class specified. Classes don't enforce any code organization — for example, you can have functions returning classes, or you can have multiple classes per file. Here's an example of how ad hoc the creation of a class can be: it's just an expression returned from an arrow function. This pattern is called a mixin.
const withAuthentication = (cls) =>
class extends cls {
authenticate() {
// …
}
};
class Admin extends withAuthentication(Person) {
// …
}
Static properties are created by prepending static. Private fields and methods are created by prepending a hash # (not private). The hash is an integral part of the element's name, and distinguishes it from a regular string-keyed property. (Think about # as _ in Python.) Unlike most other languages, there's absolutely no way to read a private element outside the class body — not even in derived classes.
For a detailed guide on various class features, you can read the guide page.