| Here's a simple example of a JavaScript class with a static method, suitable for use in Node.js: // ExampleClass.js
class ExampleClass {
// Constructor method
constructor(name) {
this.name = name;
}
// Instance method
greet() {
return `Hello, ${this.name}!`;
}
// Static method
static sayHelloToEveryone() {
return 'Hello, everyone!';
}
}
// Export the class so it can be used in other files
module.exports = ExampleClass;
How to Use the Class in Node.js: You can use this class in another file by requiring it and creating an instance of the class. // app.js
const ExampleClass = require('./ExampleClass');
// Creating an instance of the class
const instance = new ExampleClass('Alice');
// Calling the instance method
console.log(instance.greet()); // Output: Hello, Alice!
// Calling the static method
console.log(ExampleClass.sayHelloToEveryone()); // Output: Hello, everyone!
Explanation: - Constructor Method: The
constructor method is called when you create a new instance of the class. It initializes the instance with properties, such as name. - Instance Method: The
greet method is an instance method that operates on a specific instance of the class. It uses the this keyword to access the instance's properties. - Static Method: The
sayHelloToEveryone method is a static method, meaning it belongs to the class itself, not to any particular instance. You can call it without creating an instance of the class.
This is a basic example, but it shows the fundamental structure of a class with both instance and static methods in Node.js. |