Chapter 7: OOP Using JavaScript
32 slides · use ←/→ or Space to navigate, F for fullscreen.
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
Object-oriented programming in JavaScript — classes, instances, prototypes, animation loops and the benefits of OOP.
What is Object-Oriented Programming?
The OOP paradigm and its four pillars.
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.
| Pillar | Meaning |
|---|---|
| Encapsulation | Bundle data and methods into a single class unit. |
| Inheritance | Child classes extend parent class properties/methods. |
| Polymorphism | Same interface, different behaviour per object type. |
| Abstraction | Hide complexity; expose only what is necessary. |
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
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 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.();
Class Syntax vs Constructor Function
Two ways to define objects, and the trade-offs between them.
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();
}
}
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 vs Constructor Function
| Feature | class | function |
|---|---|---|
| Syntax | Cleaner | Verbose |
| Methods on | Prototype | Each instance |
| Memory | Efficient | Less efficient |
| Inheritance | extends | Prototype chain |
| Readability | Higher | Lower |
Understanding the trade-offs
| class syntax — recommended | Constructor function — legacy |
|---|---|
|
Methods defined once on the prototype, shared by all instances Supports static methods, getters and setters natively Uses extends for clean inheritanceClass 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 |
Activity — complete the code
Compare class syntax with the constructor function style.
// Class syntax: methods live on theclass Player {constructor(x, y) { this.x = x; this.y = y; }update() { this.x += 1; }}// Constructor function: methods are re-created for everyfunction Enemy(x, y) {this.x = x;this.y = y;this.update = () { this.x += 1; };}// Inheritanceclass Boss Player {}
The Animation Loop
Continuous rendering with requestAnimationFrame().
The Animation / Game Loop — Concept
How continuous rendering works in a browser:
- Start — call
animate()orgameLoop(). - Update — move objects, change state.
- Clear —
ctx.clearRect()to wipe the canvas. - Draw — render all objects.
- requestAnimationFrame(loop) — the loop repeats at frames per second.
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
| Step | Action |
|---|---|
| 1. Update state | Call update() to advance position, size or other properties. |
| 2. Clear canvas | Erase the previous frame so old drawings do not persist. |
| 3. Redraw | Call draw() to paint the object in its new position. |
| 4. Schedule next | Pass the function to rAF; the browser calls it before the next paint. |
Activity — complete the code
Complete the animation loop.
const animatedObject = new AnimatedObject(100, 100, 10, "teal");function animate() {// 1. Update stateanimatedObject.();// 2. Wipe the canvasctx.(0, 0, canvas.width, canvas.height);// 3. Redraw the objectanimatedObject.(ctx);// 4. Schedule the next frame(animate);}animate(); // kick off the loop
The Game Loop
Managing multiple game objects simultaneously.
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();
| Concept | Detail |
|---|---|
| Array of objects | Store all game entities in one array for easy iteration. |
| forEach update | Call update() on every object before any drawing occurs. |
| forEach draw | After all updates, draw all objects in the correct order. |
| Scalability | Add or remove objects from the array without changing the 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 firstgameObjects.(obj => obj.update());// Draw phase — then draw allgameObjects.(obj => obj.draw(ctx));(gameLoop);}gameLoop();
Extending the Constructor Prototype
Adding shared methods to all instances efficiently.
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
classkeyword (ES6+) uses prototype inheritance internally — it is syntactic sugar.
constructor function ──▶ prototype object
▲ ▲ ▲
instance1 instance2 instance3
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());
| Point | Detail |
|---|---|
| Constructor sets data | Properties (name, birthdate) live on each individual instance. |
| Prototype adds behaviour | calculateAge() is shared — not duplicated for each person. |
| Automatic access | Both ammar and iman can call calculateAge() via the prototype chain. |
| Dynamic extension | Adding to the prototype after objects are created still works on them. |
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 instancesPerson..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.());
Working with Multiple Object Instances
Creating and managing arrays of game objects.
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));
| Concept | Detail |
|---|---|
| Uniform interface | All objects share update() and draw() — the loop code stays simple regardless of object type. |
| Dynamic management | Push new objects or splice old ones from the array without rewriting the loop. |
| Scalability | Hundreds of enemies, projectiles and power-ups can be managed with the same loop. |
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 uniformlygameObjects.forEach(obj => obj.());gameObjects.forEach(obj => obj.(ctx));
Benefits of OOP & Summary
Why use OOP in JavaScript, and the lecture summary.
Benefits of OOP — Part 1
| Benefit | Detail |
|---|---|
| Modular code | Objects can be defined and developed independently — divide a large codebase into manageable, self-contained units. |
| Abstraction | Hide complex implementation details inside a class; expose only a clean, easy-to-use public interface. |
| Code reuse | Define a class once and instantiate it as many times as needed — eliminating copy-paste duplication. |
| Inheritance | Child classes extend parent classes to gain their properties and methods, minimising redundant code. |
Benefits of OOP — Part 2
| Benefit | Detail |
|---|---|
| Polymorphism | Objects of different types respond to the same method call in their own way — enabling flexible, extensible code. |
| Readable code | Class-based code closely mirrors real-world concepts, making it intuitive for developers joining the project. |
| State management | Each object tracks its own state internally, reducing reliance on global variables and lowering bug risk. |
| Improved testing | Objects can be tested in complete isolation; a bug in one class does not require re-testing unrelated code. |
Lecture Summary
| # | Takeaway |
|---|---|
| 1 | Class syntax — use the class keyword with a constructor to define object blueprints cleanly. |
| 2 | Object instances — use new to create independent instances, each with its own property values. |
| 3 | Animation loop — requestAnimationFrame() drives smooth 60fps rendering on the canvas. |
| 4 | Game loop — iterate an array of game objects each frame: update all, then draw all. |
| 5 | Prototype extension — add shared methods to all instances by extending the constructor prototype. |
| 6 | OOP benefits — modularity, reuse, abstraction, inheritance, polymorphism and testability. |
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