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.

Related posts:

  1. Object Oriented JavaScript: Inheritance
  2. Quick Look at JavaScript Objects
  3. OOP JavaScript: Accessing Public Methods in Private Methods
This entry was posted in javascript, micro tutorial and tagged , , , , . Bookmark the permalink.

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">