Course contentsShow
← JavaScript
Lesson 1826 of 2,72338. Object-Oriented PatternsFree lesson

Practical Composition Example: Building a Game Entity

Walk through composing position, renderable, and movable behaviors into a flexible game object without inheritance.

Practical Composition Example: Building a Game Entity

You'll learn how to compose independent behaviors into a flexible game object without using inheritance.

The Core Idea

Instead of creating a deep inheritance hierarchy (GameObject → MovableObject → Player), you'll build a game entity by mixing together small, focused behaviors. Each behavior is a function that adds specific capabilities to an object: position tracking, rendering, movement, etc.

Think of it like building with LEGO blocks. Rather than inheriting from a giant "super block," you snap together small, interchangeable pieces to create exactly what you need.

Building Composable Behaviors

// Each behavior is a simple function that adds properties/methods
const withPosition = (x, y) => ({
  x,
  y,
  setPosition(newX, newY) {
    this.x = newX;
    this.y = newY;
  }
});

const withRenderable = (sprite) => ({
  sprite,
  render(context) {
    console.log(`Rendering ${this.sprite} at (${this.x}, ${this.y})`);
  }
});

const withMovable = (speed) => ({
  speed,
  move(dx, dy) {
    this.x += dx * this.speed;
    this.y += dy * this.speed;
  }
});

// Compose them into a game entity
function createPlayer(x, y, sprite, speed) {
  return Object.assign(
    {},
    withPosition(x, y),
    withRenderable(sprite),
    withMovable(speed)
  );
}

const player = createPlayer(0, 0, '🏃', 2);
player.move(1, 0);  // x is now 2
player.render();    // "Rendering 🏃 at (2, 0)"

Each behavior is independent and testable. Need an enemy that's positioned and movable but not renderable? Just compose those two. Need a static decoration? Use only withPosition and withRenderable.

Key Takeaway: Composition lets you build game entities by combining small, focused behaviors rather than forcing objects into rigid inheritance hierarchies, giving you maximum flexibility and reusability.