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.

Leave a Reply

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