Chapter 12. Advanced Object Construction: Creating objects

Image

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 classes come in. With classes we can create objects much more easily, and we can create objects that all adhere to the same design blueprint—meaning we can use classes to ensure each object has the same properties and includes the same methods. And with classes 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...

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:

let taxi = { 
    make: "Webville Motors",
    model: "Taxi",
    year: 1955,
    color: "yellow",
    passengers: 4,
    convertible: false,
    mileage: 281341, 
    started: false,

    start() { this.started = true;},
    stop() { this.started = false;},
    drive() {
         // drive code here
    }
};
Image

Object literals give you a convenient way to create objects anywhere in your code, but if you need to create lots of objects—say, a whole fleet of ...

Get Head First JavaScript Programming, 2nd Edition 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.