Classical inheritance and sharing functionality with Object.create()

A common approach when implementing classical inheritance in JavaScript is to define your classes like this:

You can also use an object literal and reduce repetition a bit:

And this is where things get interesting, being able to do this means we can use an object to store some common functionality and share it between our classes like this:

Now both Foo and Bar share the logFoo() and logBar() methods, the only problem is that if wanted to add any methods to either objects’ prototype we would also add it to the another because they both share the same reference to the shared object.

Here’s where Object.create() becomes useful as it allows us to avoid this unwanted behaviour. Instead of setting each class’ prototype directly to the shared variable we use Object.create(shared) and our code behaves as expected:

The same principle is applied when you want to inherit functionality in one class from another through the prototype object. Instead of doing this:

Foo.prototype = Bar.prototype;

You would do:

Foo.prototype = Object.create(Bar.prototype);

Why? The same reason as before, without using Object.create() any changes to one of the classes’ prototype will affect the other which is something you don’t want most of the times.