Declaring a class
Classes are usually created with class declarations.
class MyClass {
// class body...
}
Within a class body, there are a range of features available.
class MyClass {
// Constructor
constructor() {
// Constructor body
}
// Instance field
myField = "foo";
// Instance method
myMethod() {
// myMethod body
}
// Static field
static myStaticField = "bar";
// Static method
static myStaticMethod() {
// myStaticMethod body
}
// Static block
static {
// Static initialization code
}
// Fields, methods, static fields, and static methods all have
// "private" forms
#myPrivateField = "bar";
}
If you came from a pre-ES6 world, you may be more familiar with using functions as constructors. The pattern above would roughly translate to the following with function constructors:
function MyClass() {
this.myField = "foo";
// Constructor body
}
MyClass.myStaticField = "bar";
MyClass.myStaticMethod = function () {
// myStaticMethod body
};
MyClass.prototype.myMethod = function () {
// myMethod body
};
(function () {
// Static initialization code
})();
Note: Private fields and methods are new features in classes with no trivial equivalent in function constructors.
Constructing a class
After a class has been declared, you can create instances of it using the new operator.
const myInstance = new MyClass();
console.log(myInstance.myField); // 'foo'
myInstance.myMethod();
Typical function constructors can both be constructed with new and called without new. However, attempting to "call" a class without new will result in an error.
const myInstance = MyClass(); // TypeError: Class constructor MyClass cannot be invoked without 'new'Class declaration hoisting
Unlike function declarations, class declarations are not hoisted (or, in some interpretations, hoisted but with the temporal dead zone restriction), which means you cannot use a class before it is declared.
new MyClass(); // ReferenceError: Cannot access 'MyClass' before initialization
class MyClass {}
This behavior is similar to variables declared with let and const.
Class expressions
Similar to functions, class declarations also have their expression counterparts.
const MyClass = class {
// Class body...
};
Class expressions can have names as well. The expression's name is only visible to the class's body.
const MyClass = class MyClassLongerName {
// Class body. Here MyClass and MyClassLongerName point to the same class.
};
new MyClassLongerName(); // ReferenceError: MyClassLongerName is not defined