A classless society, revisited

We just learned how to emulate the traditional OOP inheritance mechanism. But it's important to note that in JavaScript, that is only one valid approach to create objects that are related to each other.

It was Douglas Crockford who came up with another clever solution, which allows objects to inherit from each other directly. It's a native part of JavaScript by now – it's the Object.create() function, and it works like this:

Object.create = function(o) {
  var F = function() {};
  F.prototype = o; 
  return new F();
};

We learned enough now to understand what's going on. Let's analyze an example:

 var vehicle = {}; vehicle.drive = function () { console.log('vrooom...'); }; var car = Object.create(vehicle); car.honk ...

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.