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

Chapter 7: OOP Using JavaScript

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

Reading view

Jump to a lesson deck: What is Object-Oriented Programming? Creating Classes & Instances Class Syntax vs Constructor Function The Animation Loop The Game Loop Extending the Constructor Prototype Working with Multiple Object Instances Benefits of OOP & Summary

Chapter 7: OOP Using JavaScript
Fullscreen for presentation · Print / PDF for a handout
1 / 32
Chapter 7

Chapter 7: OOP Using JavaScript

Object-oriented programming in JavaScript — classes, instances, prototypes, animation loops and the benefits of OOP.

Lesson

What is Object-Oriented Programming?

The OOP paradigm and its four pillars.

What is Object-Oriented Programming?

What is Object-Oriented Programming?

A programming paradigm based on objects and classes. OOP organises software around data (objects) rather than functions and logic. In JavaScript, classes provide a clean syntax to define objects with shared behaviour.

PillarMeaning
EncapsulationBundle data and methods into a single class unit.
InheritanceChild classes extend parent class properties/methods.
PolymorphismSame interface, different behaviour per object type.
AbstractionHide complexity; expose only what is necessary.
What is Object-Oriented Programming?

Activity — complete the code

Name the four pillars of object-oriented programming.

// OOP pillars
// : bundle data and methods into one unit
// : child classes extend parent classes
// : same interface, different behaviour
// : hide complexity, expose only what is needed

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

Lesson

Class Syntax vs Constructor Function

Two ways to define objects, and the trade-offs between them.

Class Syntax vs Constructor Function

AnimatedObject Class

A reusable class for canvas-based animations.

class AnimatedObject {
  constructor(x, y, size = 10, color) {
    this.x = x;
    this.y = y;
    this.size = size;
    this.color = color;
    this.velocity = 1;
  }

  update() {
    this.x += this.velocity;
    this.y += this.velocity;
    this.size = 10 + 5 * Math.sin(Date.now() / 1000);  // pulse
  }

  draw(ctx) {
    ctx.fillStyle = this.color;
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI);
    ctx.fill();
  }
}
Class Syntax vs Constructor Function

Player: Constructor Function Style

An alternative way to define objects using functions.

function Player(x, y, size, color, ctx) {
  this.x = x;
  this.y = y;
  this.size = size;
  this.color = color;
  this.velocity = 1;
  this.ctx = ctx;

  this.update = function () {
    this.x += this.velocity;
    this.y += this.velocity;
  };

  this.draw = function () {
    ctx.fillStyle = this.color;
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI);
    ctx.fill();
  };
}
Class Syntax vs Constructor Function

Class vs Constructor Function

Featureclassfunction
SyntaxCleanerVerbose
Methods onPrototypeEach instance
MemoryEfficientLess efficient
InheritanceextendsPrototype chain
ReadabilityHigherLower

Understanding the trade-offs

class syntax — recommendedConstructor function — legacy
Methods defined once on the prototype, shared by all instances
Supports static methods, getters and setters natively
Uses extends for clean inheritance
Class bodies run in strict mode automatically
More readable, closer to Java/C++
Methods are re-created for every new instance (more memory)
Familiar to developers used to older JavaScript patterns
Inheritance requires manual prototype chaining
Works in older environments without transpiling
Flexible: can return different object types
Class Syntax vs Constructor Function

Activity — complete the code

Compare class syntax with the constructor function style.

// Class syntax: methods live on the
class Player {
constructor(x, y) { this.x = x; this.y = y; }
update() { this.x += 1; }
}
 
// Constructor function: methods are re-created for every
function Enemy(x, y) {
this.x = x;
this.y = y;
this.update = () { this.x += 1; };
}
 
// Inheritance
class Boss Player {}

Lesson

The Animation Loop

Continuous rendering with requestAnimationFrame().

The Animation Loop

The Animation / Game Loop — Concept

How continuous rendering works in a browser:

  1. Start — call animate() or gameLoop().
  2. Update — move objects, change state.
  3. Clear — ctx.clearRect() to wipe the canvas.
  4. Draw — render all objects.
  5. requestAnimationFrame(loop) — the loop repeats at frames per second.
The Animation Loop

Creating an Animation Loop

requestAnimationFrame() schedules a function to run before the next screen repaint — typically 60 times per second, making it ideal for smooth animations.

// Create an animated object instance
const animatedObject = new AnimatedObject(100, 100, 10, 'teal');

// Define our animation loop
function animate() {
  // 1. Update state
  animatedObject.update();

  // 2. Wipe the canvas
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // 3. Redraw the object
  animatedObject.draw(ctx);

  // 4. Schedule the next frame
  requestAnimationFrame(animate);
}

animate();   // kick off the loop
StepAction
1. Update stateCall update() to advance position, size or other properties.
2. Clear canvasErase the previous frame so old drawings do not persist.
3. RedrawCall draw() to paint the object in its new position.
4. Schedule nextPass the function to rAF; the browser calls it before the next paint.
The Animation Loop

Activity — complete the code

Complete the animation loop.

const animatedObject = new AnimatedObject(100, 100, 10, "teal");
 
function animate() {
// 1. Update state
animatedObject.();
 
// 2. Wipe the canvas
ctx.(0, 0, canvas.width, canvas.height);
 
// 3. Redraw the object
animatedObject.(ctx);
 
// 4. Schedule the next frame
(animate);
}
 
animate(); // kick off the loop

Lesson

The Game Loop

Managing multiple game objects simultaneously.

The Game Loop

Creating a Game Loop

A game loop extends the animation loop concept to handle multiple objects — updating and drawing each in sequence every frame.

// Array holds all active game objects
const gameObjects = [
  new Player(50, 50, 11, 'red', ctx),
  new Enemy(200, 100, 10, 'purple', ctx),
  new Enemy(300, 100, 10, 'green', ctx),
];

function gameLoop() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // Update phase
  gameObjects.forEach(obj => obj.update());

  // Draw phase
  gameObjects.forEach(obj => obj.draw(ctx));

  requestAnimationFrame(gameLoop);
}

gameLoop();
ConceptDetail
Array of objectsStore all game entities in one array for easy iteration.
forEach updateCall update() on every object before any drawing occurs.
forEach drawAfter all updates, draw all objects in the correct order.
ScalabilityAdd or remove objects from the array without changing the loop.
The Game Loop

Activity — complete the code

Complete the game loop that manages multiple objects.

const gameObjects = [
new Player(50, 50, 11, "red", ctx),
new Enemy(200, 100, 10, "purple", ctx),
];
 
function gameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
 
// Update phase — update all first
gameObjects.(obj => obj.update());
 
// Draw phase — then draw all
gameObjects.(obj => obj.draw(ctx));
 
(gameLoop);
}
 
gameLoop();

Lesson

Extending the Constructor Prototype

Adding shared methods to all instances efficiently.

Extending the Constructor Prototype

Extending the Constructor Prototype

Every constructor function has a prototype object. Methods added to the prototype are shared across all instances — saving memory and keeping code DRY.

  • Methods on the prototype are defined once and inherited by all instances.
  • Adding to the prototype after creation updates all existing instances.
  • More memory-efficient than defining methods inside the constructor.
  • The class keyword (ES6+) uses prototype inheritance internally — it is syntactic sugar.
constructor function ──▶ prototype object
                              ▲      ▲      ▲
                          instance1 instance2 instance3
Extending the Constructor Prototype

Prototype Extension: Code Example

function Person(name, birthdate) {
  this.name = name;
  this.birthdate = birthdate;
}

// Add a method to ALL Person instances
Person.prototype.calculateAge = function () {
  const today = new Date();
  let age = today.getFullYear() - this.birthdate.getFullYear();
  const m = today.getMonth() - this.birthdate.getMonth();

  if (m < 0 || (m === 0 && today.getDate() < this.birthdate.getDate())) {
    age--;   // birthday not reached yet this year
  }
  return age;
};

const ammar = new Person('Ammar', new Date(2001, 5, 15));
const iman  = new Person('Iman',  new Date(2000, 10, 3));

console.log(ammar.calculateAge());
console.log(iman.calculateAge());
PointDetail
Constructor sets dataProperties (name, birthdate) live on each individual instance.
Prototype adds behaviourcalculateAge() is shared — not duplicated for each person.
Automatic accessBoth ammar and iman can call calculateAge() via the prototype chain.
Dynamic extensionAdding to the prototype after objects are created still works on them.
Extending the Constructor Prototype

Activity — complete the code

Complete the prototype extension example.

function Person(name, birthdate) {
this.name = name;
this.birthdate = birthdate;
}
 
// Add a method to ALL Person instances
Person..calculateAge = function () {
const today = new Date();
let age = today.getFullYear() - this.birthdate.();
return age;
};
 
const ammar = new Person("Ammar", new Date(2001, 5, 15));
console.log(ammar.());

Lesson

Working with Multiple Object Instances

Creating and managing arrays of game objects.

Working with Multiple Object Instances

Working with Multiple Object Instances

// Define Enemy constructor
function Enemy(x, y, size, color, ctx) {
  this.x = x;
  this.y = y;
  this.size = size;
  this.color = color;
  this.ctx = ctx;

  this.update = function () { /* move enemy */ };
  this.draw = function () { /* draw enemy */ };
}

// Create a mixed array of objects
const gameObjects = [
  new Player(50, 50, 11, 'red', ctx),
  new Enemy(200, 100, 10, 'purple', ctx),
  new Enemy(300, 100, 10, 'green', ctx),
];

// Iterate and operate uniformly
gameObjects.forEach(obj => obj.update());
gameObjects.forEach(obj => obj.draw(ctx));
ConceptDetail
Uniform interfaceAll objects share update() and draw() — the loop code stays simple regardless of object type.
Dynamic managementPush new objects or splice old ones from the array without rewriting the loop.
ScalabilityHundreds of enemies, projectiles and power-ups can be managed with the same loop.
Working with Multiple Object Instances

Activity — complete the code

Complete the mixed array of game objects and the uniform loop.

const gameObjects = [
Player(50, 50, 11, "red", ctx),
Enemy(200, 100, 10, "purple", ctx),
new Enemy(300, 100, 10, "green", ctx),
];
 
// Iterate and operate uniformly
gameObjects.forEach(obj => obj.());
gameObjects.forEach(obj => obj.(ctx));

Lesson

Benefits of OOP & Summary

Why use OOP in JavaScript, and the lecture summary.

Benefits of OOP & Summary

Benefits of OOP — Part 1

BenefitDetail
Modular codeObjects can be defined and developed independently — divide a large codebase into manageable, self-contained units.
AbstractionHide complex implementation details inside a class; expose only a clean, easy-to-use public interface.
Code reuseDefine a class once and instantiate it as many times as needed — eliminating copy-paste duplication.
InheritanceChild classes extend parent classes to gain their properties and methods, minimising redundant code.
Benefits of OOP & Summary

Benefits of OOP — Part 2

BenefitDetail
PolymorphismObjects of different types respond to the same method call in their own way — enabling flexible, extensible code.
Readable codeClass-based code closely mirrors real-world concepts, making it intuitive for developers joining the project.
State managementEach object tracks its own state internally, reducing reliance on global variables and lowering bug risk.
Improved testingObjects can be tested in complete isolation; a bug in one class does not require re-testing unrelated code.
Benefits of OOP & Summary

Lecture Summary

#Takeaway
1Class syntax — use the class keyword with a constructor to define object blueprints cleanly.
2Object instances — use new to create independent instances, each with its own property values.
3Animation loop — requestAnimationFrame() drives smooth 60fps rendering on the canvas.
4Game loop — iterate an array of game objects each frame: update all, then draw all.
5Prototype extension — add shared methods to all instances by extending the constructor prototype.
6OOP benefits — modularity, reuse, abstraction, inheritance, polymorphism and testability.
Benefits of OOP & Summary

Activity — complete the code

Complete the OOP benefits recap.

// OOP benefits
// — define objects independently in manageable units
// Code — define a class once and instantiate it many times
// — each object tracks its own state internally
// Improved — objects can be tested in isolation