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

Creating Classes & Instances

4 slides · use ←/→ or Space to navigate, F for fullscreen.

Reading view

← Back to the full Chapter 7 deck

Creating Classes & Instances
Fullscreen for presentation · Print / PDF for a handout
1 / 4
Lesson

Creating Classes & Instances

The class keyword, constructors, this, and the new keyword.

Creating Classes & Instances

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 Classes & Instances

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.
Creating Classes & Instances

Activity — complete the code

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.();