class
Declares a class — a template for objects with shared methods.
Available since: ES2015
Syntax
class Name { constructor() { … } method() { … } }Examples
A class with a constructor and a method:
class User {
constructor(name) {
this.name = name;
}
greet() {
return `Hi, I am ${this.name}`;
}
}
const anna = new User('Anna');
console.log(anna.greet());Output:
Hi, I am AnnaClass fields with default values:
class Counter {
count = 0;
increment() {
this.count++;
return this;
}
}
const counter = new Counter();
counter.increment().increment();
console.log(counter.count);Output:
2Notes
The constructor runs automatically on new and fills in the object's properties. Class methods are shared by all its objects and are not copied into each one.
Code inside a class always runs in strict mode. A class cannot be called without new.
See also
- new — Creates a new object using a class or a constructor function.
- extends — Creates a subclass that inherits the parent's properties and methods.
- static — A method or property of the class itself, not of its objects.
- Private fields (#) — Fields and methods accessible only inside the class.
- get / set — Properties backed by functions: reading calls get, writing calls set.
In the tutorial
- Classes and objects — Classes in JavaScript: declaring a class, the constructor, fields, methods, this and creating objects with new.