Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14
Chapter 7

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.`);
  }
}
PartMeaning
class keywordDeclares the blueprint for an object.
constructor()Runs when a new instance is created.
this.propertyAssigns values to the instance.
MethodA 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.
ConceptDetail
new keywordAllocates memory and calls the constructor to initialise a fresh object.
Multiple instancesEach instance has its own copy of properties (name, age) but shares methods.
Readable codeClass syntax makes it obvious what type of object you are working with.
Easy maintenanceChange 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 method
const p1 = Person("Alice", 25);
p1.();