Classes
While JavaScript is heavily prototype-based and makes it incredibly easy to create one-off object literals (POJOs), Classes provide a structured, reusable template for creating multiple objects that share the same properties and methods.
The Class Syntax
You define a class using the class keyword.
class User {
// The constructor is called whenever a new instance is created
constructor(name, age) {
this.name = name;
this.age = age;
}
}
// Instantiate the class using the 'new' keyword
const user = new User("Lane", 100);
console.log(user.name); // Output: "Lane"
How It Works
classdeclaration: Creates the blueprint.constructor(): A special, reserved method name. It is automatically executed when a new instance of the class is created. It is primarily used to set up the initial state (this.name = ...).newkeyword: This tells JavaScript to allocate memory for a brand new object, invoke the constructor, and bind thethiskeyword inside the class to that specific new object instance.
Practical Example
A messaging application might represent a single message as a class instance, making it easy to generate thousands of consistent message objects.
class Message {
constructor(recipient, sender, body) {
this.recipient = recipient;
this.sender = sender;
this.body = body;
this.timestamp = new Date(); // Automatically assign a creation time
}
}
const myMsg = new Message("Alice", "Bob", "Are we still on for lunch?");
console.log(myMsg.timestamp); // Logs the current date/time