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

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

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

Activity — complete the code

Complete the code correctly to mark this lesson as complete automatically.

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 {}