Tuesday, May 13, 2014

How Inheritance Works in JavaScript

Inheritance is an important concept where we get the main benefit of the code re-usability. If a new class is mostly similar to an existing class, you only have to specify the differences. Patterns of code reuse are extremely important because they have the potential to significantly reduce the cost of software development. 

After all, In classical languages, objects are instances of classes, and a class can inherit from another class. We all know the old school style definition is. "Whatever Parent has is there in Child and Child can have its own".

JavaScript is a prototypal language, which means that objects inherit directly from other objects.

So as you know, Objects in JavaScript are class-free. JavaScript Objects are collections of name/value pairs having a hidden link to a prototype object. Every object is linked to a prototype object from which it can inherit properties. All objects created from object literals are linked to Object.prototype. Functions in JavaScript are also objects where function objects are linked to Function.prototype.(which intern linked to Object.prototype)

Let me explain, what is meant by prototype.

The prototype relationship is a dynamic relationship. If we add a new property to a prototype, that property will immediately be visible in all of the objects that are based on that prototype.

prototype object allows us to add custom attributes and methods dynamically. Let's crack some code. Here I add a method and an attribute to the Person object using prototype.

Copy and paste the code in a text file, save it .html extension and run this in your favorite browser.


If you understand how prototype behaves then its easy to understand how Inheritance works in JavaScript.

JavaScript includes a prototype linkage feature that allows one object to inherit the properties of another. When used well, this can reduce object initialization time and memory consumption.

Here we go. 

OK, Hope you got an idea of how Inheritance works in JavaScript.

What if we need to override the salary function in the parent class. Please refer line numbers 42-46.

Hope this simple program would shed some light.

A good book about JavaScript is: The JavaScript: The Good Parts by Douglas Crockford.

Good Luck Dev Folks!


No comments:

Post a Comment