Object Oriented JavaScript: Inheritance

Objects and JavaScript

JavaScript, being a functional language, differs from most of the procedural/object oriented languages we know. The object oriented approach in JavaScript is rather strange. However there is much power in making objects! The syntax is really odd and there are several approaches.

Literal Notation

As many of you may know the most used notation is the JSON (JavaScript Object Notation).

{ 'key1' : 'val1'
, 'key2' : 'val2'
, 'key3' : 'val3'
}

Of course this is the very basic example. You can use as value any JavaScript object – another similar object or a function.

{ 'key1' : 'val1'
, 'key2' : { 'inner_key1' : 'inner_val1' }
, 'key3' : function() {
			return 10 + 5;
		 }
}

The two examples above are showing an anonymous object in JavaScript, but you can assign this code to some variable.

var myObject = 
	{ 'key1' : 'val1'
	, 'key2' : 'val2'
	, 'key3' : 'val3'
	}

or

var myObject =
	{ 'key1' : 'val1'
	, 'key2' : { 'inner_key1' : 'inner_val1' }
	, 'key3' : function() {
				return 10 + 5;
			 }
	}

and then you can call the properties of these objects with the ‘.’ operator:

myObject.key1;
myObject.key2.inner_key1;
myObject.key3();

So far so good – this is the literal object notation in JavaScript. However there is another “objects” in JavaScript.

Objects and Functions in JavaScript

Actually in JS the functions are also objects (classes). So you can define a function and then define another function inside or use the “this” operator.

var a = function(name)
{
	this.name = name;
 
	this.print = function() {
		alert(this.name);	
	}
}

Then you can make a new instance of this “class”.

var myObject = new a('hello world');
var anotherObject = new a('some test');
 
myObject.print(); // will print the string "hello world"
anotherObject.print(); // will print the string "some test"

Thus the function “a” defined within the code “var a = function(name) …” is a class in JavaScript. You can make instances (objects) of this class with the “new” operator.

You can use another notation for defining the function “a”, so both can be used and it’s up to you to decide which one is more convenient.

function a(name) 
{
	this.name = name;
 
	this.print = function() {
		alert(this.name);	
	}	
}

Prototypes

JS gives you more power. In most of the languages you’ve to define the class first and then make objects. In JS you can define a “class” then make some objects and then add some properties to the class by using the prototype.

var a = function(name) 
{
	this.name = name;
}
 
var myObj = new a('hello world');
 
a.prototype.print = function() {
	alert(this.name);	
}
 
myObj.print();

So you can see how you can add functions and properties to an already defined class using the prototype. Thus you can call the “print” function on the myObj object.

Inheritance

The prototype built-in property can be used to make use of one of the main OOP features – inheritance.

var SuperClass = function()
{
	this.superFunction = function() {
		return 'function in Super Class';	
	}
}
 
var sup = new SuperClass();
sup.superFunction(); // will return the string "function in Super Class"

Now you can add one more class and set its prototype to the SuperClass

var SubClass = function()
{
	this.subFunction = function() {
		return 'function in Sub Class';	
	}	
}
 
SubClass.prototype = new SuperClass();

Thus you make SubClass inherit from SuperClass. Now you can call the SuperClass properties from any SubClass object.

var sub = new SubClass();
sub.superFunction(); // will return the string "function in Super Class"
sub.subFunction(); // will return the string "function in Sub Class"

Even more! You can add properties to the super class with prototype.

SuperClass.prototype.myFunc = function() {
	return 'my new function';	
}

And then call it from the sub class:

sub.myFunc(); // will return the string "my new function"

Override a Function

What happens if you have the same function name in both classes. Actually this overrides the method in the sub class.

var SuperClass = function()
{
	this.myFunc = function() {
		return 'function in Super Class';	
	}
}
 
var SubClass = function()
{
	this.myFunc = function() {
		return 'function in Sub Class';	
	}	
}
 
SubClass.prototype = new SuperClass();
 
var sub = new SubClass();
sub.myFunc(); // will return the string "function in Sub Class"

while

var sup = new SuperClass();
sup.myFunc(); // will return the string "function in Super Class"

Conclusion

Now you know there are classes, inheritance and overrides in JavaScript – thus you can improve your object oriented JavaScript!

14 thoughts on “Object Oriented JavaScript: Inheritance

  1. Hi,

    Although if you reduce it to the essence the information in your article is good, I would have a few observations to make:

    1. The notation below is extremely, extremely bad. The comma should stay at the end of your key-value pairs, and not at the beginning. This is extremely prone to errors and especially typos (see here, an excellent article about many important best practices in JS).

    { ‘key1’ : ‘val1’
    , ‘key2’ : ‘val2’ // Very wrong placed comma!
    ‘key3’ : ‘val3’, // Should be like this.
    ‘…’ : ‘…’
    }

    2. Also, since I’m a grammar Nazi, in my opinion improving your English would make your articles not only more serious and credible, but also easier to read:

    a. you’re constantly using “than” instead of “then”. “Than” is for comparison (“JS is better than PHP”), while “then” is for a succession of events (“I’m writing this code, then I’m having a beer.”)

    b. you’re contracting the auxiliary verb “have” in wrong contexts: you have to use it as a whole word when expressing obligation, something mandatory. You don’t say “you‘ve to get good grades in school”, but “you have to get good grades…”. However, contraction can be used when you’re using past tenses: “You‘ve been doing great lately!”

    Cheers!

  2. @Valikika – Thank you for your grammatical corrections. I apologize for them and I hope you can understand me as I’m not a native English speaker.

    However about the notation I don’t agree. As you may know trailing comma in JavaScript is a syntax error, that is why I use this notation that helps me add more rows without the fear to forget a comma on the end of the line. Actually this notation is widely used in Node.js documentation.

  3. Hi,

    Is it possible to add a function to the super class.

    I want to add a function to Date object, I don’t want to use prototype.

  4. Hi Jayakumar,

    yes indeed you can use the prototype object:

    Date.prototype.myFunc = function () { alert('test') }

    However this is a bad practice and should be avoided. Better approach, in my opinion, is to inherit the Date object:

    var myDate = function() {
    	this.myFunc = function() { alert('test') };
    }
    
    myDate.prototype = new Date();
    
    var d = new myDate();
    
    d.myFunc();
    
  5. I’m really unimpressed with Valikika’s comment, in your infinite wisdom you have failed to see that the subject is the pont of the original post and not it’s grammar. We’ve all understood and for those that didn’t know about inheritance this is a positive learning. Once again somebody has appointed themselves as an authority in a particular subject in this case the presumption is that they are the internets resident Grammar Cop, nice one Stoimen your post on inheritance was/is explained very well…thx.

  6. Thanks a lot for making things simple. This was an awesome tutorial to qucikly brush up ur concepts. You rock \m/

Leave a Reply

Your email address will not be published. Required fields are marked *