Skip to Main Content
Head First JavaScript Programming, 2nd Edition
book

Head First JavaScript Programming, 2nd Edition

by Eric Freeman, Elisabeth Robson
August 2024
Beginner content levelBeginner
662 pages
17h 50m
English
O'Reilly Media, Inc.
Content preview from Head First JavaScript Programming, 2nd Edition

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Head First JavaScript Programming

Head First JavaScript Programming

Eric T. Freeman, Elisabeth Robson
Head First HTML and CSS, 2nd Edition

Head First HTML and CSS, 2nd Edition

Elisabeth Robson, Eric Freeman

Publisher Resources

ISBN: 9781098147938Errata Page