Creating objects

Let's dive into code a bit, shall we? How could we set up our code in order to allow us to create our myCar object, ending up with an object that is a Car and can therefore honk and drive?

Well, in the most simple sense, we can create our object completely from scratch, or ex nihilo if you prefer the boaster expression.

It works like this:

var myCar = {};

myCar.honk = function() {
  console.log('honk honk');
};

myCar.drive = function() {
  console.log('vrooom...');
};

This gives us an object called myCar that is able to honk and drive:

myCar.honk(); // outputs "honk honk"
myCar.drive(); // outputs "vrooom..."

However, if we were to create 30 cars this way, we would end up defining the honk and drive behaviour of every single ...

Get The Node Craftsman Book 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.