O'Reilly logo

Head First JavaScript Programming by Elisabeth Robson, Eric T. Freeman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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. What other issues might ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required