Chapter 12. Creating objects
Advanced Object Construction
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:
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.