Fork me on GitHub

Javascript Inheritance

August 13, 2014

tags: javascript code

There are plenty of articles and docs that describe the differences, strengths, and weaknesses of javascript prototypal inheritance compared to more traditional inheritance schemes in other languages. Goodness knows there are many ways to get it wrong. I saw a new one in a project recently. What happens when you do the following?

var Parent = function(){}
var Child = function(){}

// :-/
Child.prototype = new Parent()

There was a major bug in this project related to data leaking across multiple instances of the Child class. We can see the bug in action if we continue the example above:

var child1 = new Child()
var child2 = new Child()

child1.a = "yo"
// prints "hi" - as I would expect = "tom"
// prints "tom" - NOT as I would expect

Primitive attributes would behave as expected but complex values would be shared across instances when the prototype chain was set up this way.

As for how this should have been done, I used an example from the MDN docs and node.js' util module as guides.

var Parent = function(){}
var Child = function(){

Child.prototype = Object.create(Parent.prototype, {constructor: Child})

or using node.js' util.inherits

var util = require("util")

var Parent = function(){}
var Child = function(){

util.inherits(Child, Parent)

Discussion, links, and tweets

a small avatar image of Tom

I am a software developer in Los Angeles.