Monday, October 6, 2014

Understanding prototypal inheritance

Many developers coming from a classical inheritance model find it difficult to grasp JavaScript's prototypal inheritance. In this post, I will explain how inheritance is achieved in JavaScript and what pitfalls to avoid.

Consider the following code where we create an instance of "Class" using code that looks like classical inheritance
function Class() {
    this.obj2 = {c: 'c'}
}

Class.prototype = {
    primitive: 'a',
    obj: { a: 'a' },
    arr: [1,2,3]
};

var inst1 = new Class();
var inst2 = new Class();

The following diagram explains which objects are being created. Solid lines are direct links and dashed lines are chaining objects through the prototype.


An equivalent way of creating an instance, in a more prototypal, albeit more verbose fashion is the following:
// Create an empty object chaining it to Class.prototype
var inst1 = Object.create(Class.prototype);
// Initialize the object using the constructor
Class.call(inst1);

The important thing to understand is that the prototype object is shared by all instances. A common pitfall is to instantiate an object/array on the prototype without realizing that mutating that object will modify it for all instances. In our example, the {a: 'a'} object and the [1,2,3] array is shared among the instances, whereas each instance has its own copy of {c: 'c'}
// The two instances share the same instance of obj
// which may be unexpected
inst1.obj.a = 'b';
console.log(inst1.obj); // {a: 'b'}
console.log(inst2.obj); // {a: 'b'}

// same for arrays (since array is a mutable object)
inst1.arr.push(4);
console.log(inst1.arr); // [1,2,3,4]
console.log(inst2.arr); // [1,2,3,4]

// to get around this, create the child objects in constructor
// now changing obj2 in instance1 does not affect instance2
inst1.obj2.c = 'd';
console.log(inst1.obj2); // {c: 'd'}
console.log(inst2.obj2); // {c: 'c'}
Note that this problem doesn't occur when sharing primitives on the prototype. When we read a property from an object, it will first look for the property in the specified object, if it doesn't find it, it will go up the prototype chain looking for that object. However, when you write to an object, it always writes to the specified object, not the prototype. For example

// Here we creating a new property on inst1, which now shadows 
// the "primitive" property on "Class.prototype"
inst1.primitive = 'b';
// Still reading from Class.prototype
console.log(inst2.primitive); // 'a'
// Read "obj" from the prototype and then write over the "a" 
// property on that "obj" (from the prototype)
inst1.obj.c = 5;
// Create a new object that writes a new "obj" property on inst2 
// directly and shadows "obj" on the prototype
inst2.obj =  {c: 6};

Lessons to learn:

  • Initializing immutable objects on a prototype keeps a single copy, so it saves memory and initialization code
  • Don't share mutable objects on the prototype unless you want changes in one instance to reflect in all instances.
  • Initializing primitives on the prototypes is always OK, because they can't be mutated directly through instances
 If you'd like to play around with the above code, go to http://jsfiddle.net/mendesjuan/cdaq5b11/3/

3 comments:

  1. Wonderful explanation. I understand inheritance a bit better now. Would you mind looking at your older post on JavaScript inheritance done right? The post is a bit old and I wondered if you still employ the technique you outlined there. And the last question in the comment section was never answered. Could you please go over it too? I would really appreciate it.

    ReplyDelete
    Replies
    1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Training in Chennai . or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry. ES6 Training in Chennai

      Delete
  2. Unknown, I use different libraries to create inheritance, but they all use the same technique. What is really out of date on that post is the fact that you don't need a surrogate constructor anymore, you can just use `var SubProto = Object.create(ParentProto)` to chain the prototypes

    ReplyDelete