Creating Classes & Instances
The class keyword, constructors, this, and the new keyword.
Creating a Class for an Object
Use the class keyword followed by the class name and curly braces containing the class definition. Inside, define a constructor and methods.
class Person {
constructor(name, age) {
this.name = name; // property
this.age = age; // property
}
greet() { // method
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
| Part | Meaning |
|---|---|
class keyword | Declares the blueprint for an object. |
constructor() | Runs when a new instance is created. |
this.property | Assigns values to the instance. |
| Method | A function defined inside the class. |
Creating Instances of an Object
Use the new keyword to instantiate objects.
const person1 = new Person('Alice', 25);
const person2 = new Person('Bob', 30);
person1.greet(); // Hello, my name is Alice and I am 25 years old.
person2.greet(); // Hello, my name is Bob and I am 30 years old.
| Concept | Detail |
|---|---|
new keyword | Allocates memory and calls the constructor to initialise a fresh object. |
| Multiple instances | Each instance has its own copy of properties (name, age) but shares methods. |
| Readable code | Class syntax makes it obvious what type of object you are working with. |
| Easy maintenance | Change the class once — all instances automatically reflect the update. |
Activity — complete the code
Complete the code correctly to mark this lesson as complete automatically.
Complete the class definition and create an instance.
Person {(name, age) {this.name = name;this.age = age;}greet() {console.log("Hello, my name is " + this.name);}}// Create an instance and call a methodconst p1 = Person("Alice", 25);p1.();