Basic article on Class and its inheritance in Javascript.

This is a basic article on OOPS way in javascript. Just trying to get you all know about the concept of class and its inheritance in Javascript. This is a good way to introduce yourself to the advanced concept in javascript one of them is OOPS methodology in Javascript

OOPS Concepts(Class and inheritance) in Javascript:

This is a basic resource on OOPS way in javascript. Just trying to get you all know about the concept of class and its inheritance in Javascript.

How to call a class in Javascript:

We can declare a class and create its object in the below manner:

function Programming(language, concept)
this.language = language;
this.concept = concept

//this creates a class named Programming. Now note:

var programmer = new Programming("C#", "OOPS")

//Note that the object programmer of type programming will be created. If we donot provide 'new' keyword it will not implement the class aspect of Object oriented Javascript.

alert(programmer.language) // Output = C#
alert(programmer.concept) // Output = OOPS

Inheritance feature in Javascript

Inheritance is achieved by using the Prototype of the class. Prototype is used to relate the 2 classes to achieve inheritance.

We will use the same class as we used in above example ie; class programming

function Environment(name, version)
{ = name;
this.version = version;

Environment.prototype = new Programming("C#", "OOPS");

var myEnvironment = new Environment("Visual Studio", "2012");
alert( // Output : Visual Studio
alert(myEnvironment.version) // Output: 2012
alert(myEnvironment.concept) // Output: OOPS
alert(myEnvironment.language) // Output: C#

Now whats happening behind the scenes, It looks up at the property in the class Environment. If it finds the property it will display it, otherwise it will go to class Programming because we have defined the prototype of class Environment with Programming

If we want to further extend the class Programming, we can do so as follows:

Programming.prototype.SpaceRequired = "1 GB";
alert(myEnvironment.SpaceRequired) // Output: 1 GB

If we never want our class Programming to be extended we can define our class Environment as follows:

function Environment(name, version)
this.base = Programming("C#", "OOPS"); = name;
this.version = version;

Environment.prototype = new Programming; //Output: Programming constructor is invoked and assigns language= C# and concept= OOPS. Stops further extension of class Programming.


No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: