Tag Archives: Inheritance

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.
Continue reading Object Oriented JavaScript: Inheritance

JavaScript inheritance example

JavaScript and inheritance

Almost for everybody the JavaScript way of implementing inheritance is odd. For a typical programmer it should look more C or Java like, but is not. However to give you a breve example, I’d like to make two objects, and to make the second one to inherit from the first. Thus I’d like to show how neither parent or child objects interact once they have been instanciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
	var parent = function() {};
	parent.prototype = {
		name : 'parent',
		m : 1,
		a : function() {
			console.log(this.name + ': ' + this.m);
		},
		setM : function( value ) {
			this.m = value;
		}
	};
 
	var child = function() {};
	child.prototype = new parent;
	child.prototype.name = 'child';
 
	var parentObj = new parent();
	var childObj = new child();
 
	parentObj.a();
	parentObj.setM(12);
 
	childObj.a();
	childObj.setM(3);
 
	parentObj.a();
	childObj.a();

However this describes the ability to make complex JavaScript inheritance patterns. The complete source’s here.