Javascript Inheritance

Published Oct 19, 2017

JavaScript has an interesting way of inheritance. The reason is due to its class-free nature and where every construct in the language is an object. In static languages like c#, you derive class from another class. in JavaScript you derive an object from another object. So what does this imply?

Let us break this in to a small but concrete example. Below is a tiny javascript object that represents a shape (with its properties).

var shape = { type: ‘circle’, radius: 2 };

Let us inherit this class using the JavaScript’s syntax:

var myShape = Object.create(shape); // print the properties of myShape console.log(myShape.type); // prints ‘circle’ console.log(myshape.radius); // print ‘2’

This clearly indicates the myShape “inherits” the properties from shape. Wait a minute, what just happened was, 2 objects share memory location of the properties.


Prototype inheretince

This is called prototypical inheritance. What makes it so interesting is the next steps that are uncovered below. Let us change the property value in derived object (myClass).

myClass.radius = 5;

At this point a copy is created only for the property that is updated in the inherited object. After this update the memory layout would look like:


Prototypical inheritance after change is made

Once the copy is made in derived object, the parent is property is left unchanged. To get this more concretely let us print the properties:

console.log(shape.radius); // this is still 2console.log(myShape.radius); // this is 5 now

Also note the property that did not get changed (like ‘type’) in the derived object will still continue to share the value from parent object.

Conclusion

  • In JavaScript object inherits another object
  • The derived object appears to be independent but share the properties of its parent object
  • Only when any update is made for any property, a copy is created in the in the derived object
Discover and read more posts from Madhan Ganesh L
get started
Enjoy this post?

Leave a like and comment for Madhan