EN
JavaScript - classes
0
points
In this article, we would like to show you classes in JavaScript.
Class declaration
To declare the class, you need to use class
keyword with the class name.
class ClassName {
constructor() {
// ...
}
}
Constructor
The constructor method is a special method for creating and initializing class objects.
The constructor method:
- always has the exact name
constructor
, - is executed automatically when a new class object is created,
- is used to initialize class object properties.
Practical example:
class User {
constructor(id, name, age) {
this.id = id;
this.name = name;
this.age = age;
}
}
Create class objects
When you declare a class, you can use it to create objects.
Syntax:
const User1 = new User(1, 'Tom', 23);
const User2 = new User(2, 'Kate', 22);
Runnable example:
// ONLINE-RUNNER:browser;
// class declaration
class User {
constructor(id, name, age) {
this.id = id;
this.name = name;
this.age = age;
}
}
// create class objects
const User1 = new User(1, 'Tom', 23);
const User2 = new User(2, 'Kate', 22);
// display class objects
console.log(JSON.stringify(User1));
console.log(JSON.stringify(User2));
Output:
{"id":1,"name":"Tom","age":23}
{"id":2,"name":"Kate","age":22}
Class prototype methods
Class methods are created similarly to object methods. Any number of class methods can be added right after the constructor
method. We use it as User
prototype methods.
Syntax:
class ClassName {
constructor() {
//...
}
classMethod1() {
//...
}
classMethod2() {
//...
}
}
Practical example:
In below example, we create a simple method inside User
class that displays its properties in the console.
// ONLINE-RUNNER:browser;
class User {
constructor(id, name, age) {
this.id = id;
this.name = name;
this.age = age;
}
// create class method
printUser() {
console.log(`User: ${this.name}, id: ${this.id}, age: ${this.age}`)
}
}
// create class objects
const User1 = new User(1, 'Tom', 23);
const User2 = new User(2, 'Kate', 22);
// use class method
User1.printUser();
User2.printUser();