Chapter 12. Creating objects

Advanced Object Construction

image with no caption

So far we’ve been crafting objects by hand. For each object, we’ve used an object literal to specify each and every property. That’s okay on a small scale, but for serious code we need something better. That’s where object constructors come in. With constructors we can create objects much more easily, and we can create objects that all adhere to the same design blueprint—meaning we can use constructors to ensure each object has the same properties and includes the same methods. And with constructors we can write object code that is much more concise and a lot less error prone when we’re creating lots of objects. So, let’s get started and after this chapter you’ll be talking constructors just like you grew up in Objectville.

Creating objects with object literals

So far in this book, you’ve been using object literals to create objects. With an object literal, you create an object by writing it out... well, literally. Like this:

image with no caption

Object literals give you a convenient way to create objects anywhere in your code, but when you need to create lots of objects—say a whole fleet of taxis—you wouldn’t want to type in a hundred different object literals now would you?

Brain Power

Think about creating a fleet of taxi objects. ...

Get Head First JavaScript Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.