class
Defines a class: a template for creating objects that share the same fields and methods.
Example
#class Student {
constructor(name) {
this.name = name
this.points = 0
}
addPoints(amount) {
this.points += amount
return this
}
}
const emma = new Student('Emma')
emma.addPoints(50).addPoints(30)
console.log(emma)
console.log(emma instanceof Student)Definition and usage
#The class keyword creates an object template. The constructor method runs on every new and sets the fields of the new instance through this. Methods written in the class body go onto the prototype, so every instance shares the same functions.
A class can inherit from another with extends. In a derived class’s constructor, you have to call super() before the first use of this, and super.method() calls the base class’s version of a method. Fields and methods marked static belong to the class itself, not to an instance.
Fields prefixed with # are private and only reachable from inside the class. Getters and setters (get, set) expose computed values as if they were plain properties. A class body always runs in strict mode, and unlike a function declaration, you can’t use a class before the line where it’s declared.
Syntax
#class Name {
field = value
#privateField = value
static staticField = value
constructor(param) {
this.property = param
}
method() {}
get computed() {}
set computed(value) {}
static staticMethod() {}
}
class Child extends Name {}More examples
#class User {
constructor(name) {
this.name = name
}
describe() {
return `User ${this.name}`
}
}
class Mentor extends User {
constructor(name, course) {
super(name)
this.course = course
}
describe() {
return `${super.describe()}, mentor of the ${this.course} course`
}
}
const mentor = new Mentor('Jack', 'React')
console.log(mentor.describe())
console.log(mentor)class Wallet {
#coins = 0
static withBonus(bonus) {
const wallet = new Wallet()
wallet.add(bonus)
return wallet
}
add(amount) {
if (amount <= 0) throw new RangeError('Amount must be positive')
this.#coins += amount
}
get balance() {
return `${this.#coins} coins`
}
}
const wallet = Wallet.withBonus(100)
wallet.add(25)
console.log(wallet.balance)
console.log(wallet)
console.log(Object.keys(wallet))The #coins field isn’t visible from outside, or in Object.keys(). Reading wallet.#coins outside the class is a syntax error.
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Don’t forget
new. Calling a class like a regular function, e.g.Student("Emma"), throws aTypeError. - A method passed as a callback loses
this, e.g. inbutton.addEventListener("click", game.start). Use an arrow() => game.start(), orgame.start.bind(game). - Not every piece of code needs classes. A plain object literal is enough for simple data, and a regular function for a single operation.
Related entries
#- functionDeclares a named function: a block of code with parameters that you can call any number of times and that can return a result.
- thisA keyword pointing to the object a function was called on.
- get / setProperties computed on read (get) and handled on write (set).
- Object.create()Creates a new object with the given prototype.
- throwThrows an exception: stops the current code and passes the error to the nearest catch block.
- extendsCreates a derived class that inherits another class’s methods and can extend or override them.
Spotted a mistake or missing an example? Write to us.