Class is an important and powerful concept. It allows you to create objects with unique properties and methods. Using classes helps you organize and reuse code more easily.
To initialize a class in JavaScript, we use the keyword 'class'. Here is the syntax for declaring a simple class:
class MyClass {
constructor() {
// Constructor code
}
myMethod() {
// Method code
}
}
In which, 'MyClass' is the name of the class, 'constructor' is a special method called when an object of the class is created, and 'myMethod' is any method of the class.
After declaring a class, we can create an object from it using the keyword 'new'. Here is how to create an object from the class 'MyClass':
const myObject = new MyClass();
In JavaScript, classes allow us to declare and use properties. Properties are variables associated with the class object. Here is an example of declaring and using properties in a class:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
introduce() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
const john = new Person("John", 25);
john.introduce(); // Output: Hello, my name is John and I am 25 years old.
In the above example, we have a class 'Person' with two properties 'name' and 'age'. In the constructor, we assign the values of the 'name' and 'age' parameters to the corresponding properties. The 'introduce' method is used to print out the object's information.
In addition to declaring properties, classes in JavaScript also allow us to declare and use methods. Methods are functions attached to the object of the class. Here is an example of declaring and using methods in a class:
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
getArea() {
return this.width * this.height;
}
}
const rectangle = new Rectangle(5, 10);
console.log(rectangle.getArea()); // Output: 50
In the example above, we have a class Rectangle with two properties width and height. The method getArea is used to calculate the area of the rectangle.