Jump to content

Check out our Community Blogs

Register and join over 40,000 other developers!

Recent Status Updates

View All Updates

- - - - -

Inheritance in JavaScript

oop javascript inheritance tutorial

  • Please log in to reply
1 reply to this topic

#1 Yannbane


    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 238 posts
  • Programming Language:C, Java, C++, PHP, Python, JavaScript, PL/SQL, Lisp, Assembly, Bash, Others
  • Learning:Lisp, Scheme

Posted 06 January 2013 - 05:52 AM

People have been using Javascript for more serious programs for some time now... And with that comes the need for object oriented programming and, of course, inheritance.

Javascript doesn't feature classes, but it does, however, feature constructor functions, which emulate classes. Here is an example:

//This is a basic UI element on the screen.
var Element = function(x, y, w, h)
	var el = this; //To avoid weird bugs because 'this' in various situations can change its meaning.

	el.x = x;
	el.y = y;
	el.width = w;
	el.height = h;

In order to attach a method to objects of this primitive class, you could write something along the lines of el.method = function(){...}. However, this isn't what you want to do, because then each object would get its own copy of the method!

You want to make use of Javascript's prototype pattern, like so:

//Resizes an element in place. some_el.resize(2, 2) makes it two times larger.
Element.prototype.resize = function(factor_w, factor_h)
	var el = this;

	change_width = factor_w * el.width - el.width; //Positive if the element is getting bigger (i.e. factor was higher than 1)
	change_height = factor_h * el.height - el.height; //Negative if it is getting smaller (i.e. factor was lower than 1)
	//0 if a factor was 1 (no change)

	el.width += change_width;
	el.height += change_height;

	el.x -= change_width/2;
	el.y -= change_height/2;

To instantiate such a class, just write var some_element = new Element(153, 342, 20, 100);, for example. This object does not actually have the resize() method though! What Javascript does in that case, is looking up the prototype chain to find this member or method (if it cannot be found it evaluates to undefined).

And this is the magic of the 'new' keyword in Javascript. At one point, some_element's (inaccessible) prototype property is set to Element.prototype, the constructor function's prototype, and now some_element "inherited" all of the members and methods from Element.prototype. This is not the inheritance in OOP sense, though. We want another class, for example, Button, to inherit from Element.

This new class we are creating, Button, will only add one additional member: a callback function when_clicked.

This is the code which will make Button inherit all members and methods of Element:

var Button = function(x, y, w, h, text, when_clicked)
	var b = this;

	Element.call(b, x, y, w, h);

	b.when_clicked = when_clicked;

Button.prototype = Object.create(Element.prototype);
Button.prototype.constructor = Button

Inheritance is achieved through two steps here, actually: Element.call(...) and Button.prototype = Object.create(Element.prototype).

The most interesting of those steps is Element.call(...). 'call' is a method all functions in Javascript have, and it is used to change the meaning of 'this' in those functions. Just like the 'new' keyword sets the meaning of 'this' to the object that is being created, f.call(obj) sets the meaning of this to the function's first argument, obj. So the button instance was simply passed to the Element constructor function, which in turn initialized the button object as an element!

However, this is not enough. What about methods?

Well, that's where Button.prototype = ...; comes in. Remember how Javascript traverses the prototype chain of an object to find a member that is "missing"? And how 'new' sets this prototype of an object to its constructor's prototype? Well, great, we simply added an additional node to the chain. Now it's Element.prototype >> Button.prototype >> some_button!

In order to find out how exactly Object.create works, I suggest you visit this MDN page: developer.mozilla.org/en-US/docs/Javascript/Reference/Global_Objects/Object/create.

Essentially, it creates a new object with its first parameter being the prototype of the newly-created object. It also allows for very neat things if you specify its second argument, but those are out of scope for this article, I'm afraid.

And that is it! A Button object is an Element object now.

Edited by Roger, 06 January 2013 - 09:06 AM.
added code tags

  • 0

My blog: yannbane.com. I post about programming, game development, and artificial intelligence.

#2 James360Smith


    CC Newcomer

  • Member
  • PipPip
  • 20 posts
  • Programming Language:Objective-C, PHP, JavaScript, PL/SQL, Ada, Transact-SQL, Logo, ActionScript
  • Learning:Objective-C, PHP, JavaScript, Perl, Ruby, PL/SQL, Visual Basic .NET

Posted 15 March 2013 - 01:07 AM

Hi Yannbane,


It's a great tutorial to know about inheritance in JavaScript, I like it as you write it in a simple but effective way to get understood easily.

  • 0

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download