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

Class Syntax vs Constructor Function

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

Reading view

← Back to the full Chapter 7 deck

Class Syntax vs Constructor Function
Fullscreen for presentation · Print / PDF for a handout
1 / 5
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 {}