How to make a class in JavaScript
Learn how to create a JavaScript class with a practical example. Dive in to discover how to make the most of the language's object-oriented features.
Creating a Class in JavaScript
In JavaScript, classes can be created using the class
keyword. This can be used to create new objects, as well as add methods and properties to them. The structure of a class looks like this:
class MyClass {
constructor() {
// code here
}
// other methods
}
The constructor()
method is where you can set the initial state of the class, such as setting properties and adding methods. Here's an example of a simple class that has two properties, name
and age
, and one method, getInfo()
:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
getInfo() {
console.log(`${this.name} is ${this.age} years old.`);
}
}
Once we have created the class, we can then create an instance of it like this:
const john = new Person("John", 25);
Now we can access the properties and methods of the Person
class using the john
object:
console.log(john.name); // "John"
console.log(john.age); // 25
john.getInfo(); // "John is 25 years old."
This is just a basic example of how to create a class in JavaScript. Classes can be extended and modified in various ways, such as by adding more methods or properties, or by creating subclasses that inherit from the parent class. Classes can also be used to create complex objects with multiple properties and methods that can be used to easily manipulate and access data.