Skip to Content
Course content

70: Constructor Functions

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I remember a junior developer I mentored a few years ago who was building a simple space-invaders clone. When I opened his source code, I found a file where he had manually declared twenty different object literals for his enemy fleet. Each one had the same properties—health, speed, and position—but with slightly different values. It was a nightmare to maintain. Every time he wanted to add a new property, like shieldStrength, he had to find-and-replace it across twenty different objects. He was essentially doing the work the language was designed to do for him.

Stop Repeating Yourself with Blueprints

In JavaScript, when you find yourself creating multiple objects that share the same structure, you need a blueprint. That's exactly what a constructor function is. It's not a special "type" of function—it's just a regular function—but we treat it differently. By convention, we start the name with a capital letter (PascalCase) to signal to other developers, "Hey, don't just call this; use it with the new keyword."

Let's look at how we would have fixed that space shooter code. Instead of twenty literals, we create one constructor:

function EnemyShip(type, health, speed) {
  this.type = type;
  this.health = health;
  this.speed = speed;
  this.isAlive = true;

  this.takeDamage = function(amount) {
    this.health -= amount;
    if (this.health <= 0) this.isAlive = false;
  };
}

const scout = new EnemyShip('Scout', 50, 10);
const dreadnought = new EnemyShip('Dreadnought', 500, 2);

Notice how I used this. Inside a constructor, this doesn't refer to the function itself, but to the brand-new object that is currently being created. I've personally seen plenty of bugs caused by forgetting that this is dynamic, but in the context of a constructor, it's your best friend for assigning properties.

The Magic Behind the new Keyword

You might be wondering why we can't just call EnemyShip() like a normal function. If you do that, this will point to the global object (or be undefined in strict mode), and you'll accidentally create global variables while the function returns undefined. That's a recipe for a debugging headache.

When you prepend the new keyword, JavaScript does four things behind the scenes:

  • It creates a brand new, empty object.
  • It links this new object to the constructor's prototype (which we'll dive into deeper in later lessons).
  • It sets the this keyword to point to that new object.
  • It automatically returns the object, unless you explicitly return a different object.

It's a bit of syntactic sugar, but it's powerful. It allows you to instantiate hundreds of objects with a single line of code each, ensuring they all adhere to the same shape. Just remember: if you see a function starting with a capital letter, new is almost certainly required.




📋 Practical Task

Build a Tabletop RPG Character Generator

You are building a system for a tabletop RPG. Instead of manually creating objects for every player character, create a constructor function called Character.

  • The constructor should accept name, className (e.g., "Warrior", "Mage"), and level as arguments.
  • It should assign a default experiencePoints property of 0 to every character.
  • Add a method inside the constructor called gainExperience that takes an amount, adds it to the experiencePoints, and logs a message like "Gimli gained 50 XP!".

To test your work, instantiate two different characters (e.g., a Level 1 Mage and a Level 5 Warrior) and call the gainExperience method on both to ensure they are tracking their XP independently.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.