node js classes
Node.js Classes
Node.js is a JavaScript runtime that allows developers to build server-side applications using JavaScript. Classes in Node.js are a way to define and create objects with similar properties and methods. They provide a blueprint for creating multiple instances of objects with the same structure and behavior.
To create a class in Node.js, you can use the class
keyword followed by the class name. Here is an example:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHello() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
In the example above, we define a Person
class with a constructor function that takes name
and age
as parameters. The constructor function is called when a new instance of the class is created and is used to initialize the object's properties.
The sayHello
method is defined inside the class and can be called on instances of the Person
class to print a greeting message.
To create an instance of a class, you can use the new
keyword followed by the class name and any required arguments for the constructor function. Here is an example:
const john = new Person('John', 25);
john.sayHello(); // Output: Hello, my name is John and I am 25 years old.
In the example above, we create a new instance of the Person
class called john
with the name 'John' and age 25. We then call the sayHello
method on the john
object to print the greeting message.
Classes in Node.js can also have static methods and properties that are accessed directly on the class itself, rather than on instances of the class. Static methods are defined using the static
keyword. Here is an example:
class MathUtils {
static add(a, b) {
return a + b;
}
}
console.log(MathUtils.add(2, 3)); // Output: 5
In the example above, we define a MathUtils
class with a static add
method that takes two numbers as parameters and returns their sum. The add
method can be called directly on the MathUtils
class without creating an instance of the class.
Overall, classes in Node.js provide a way to create reusable objects with shared properties and methods. They help organize code and promote code reusability and maintainability.