Monday, August 22, 2011

Implement Inheritance in NodeJs

I'm learning Nodejs these days , and coming from an OOP background, i tend to get things done closer to how i'm doing there.

So I wanted all my Nodejs objects to inherit from a base object , that provide utilities common to every other thing .. this is in OOP known as inheritance.

In JavaScript world class/inheritance isn't officially a feature of the language, but its doable, for example the following JavaScript method copies the prototype of one object to another,

function inherit (parent, descendant) {
                var sConstructor = parent.toString();
		var aMatch = sConstructor.match(/\s*function (.*)\(/);
		if(aMatch != null) {
			descendant.prototype[aMatch[1]] = parent;
		}
		for(var m in parent.prototype) {
			descendant.prototype[m] = parent.prototype[m];
		}
The result of this method is, all functions implemented by the parent will now be added to the descendant.

Fine so far, now how to get this done in Nodejs.

NodeJs combine/organize code into what so called "Modules" , and each module should export (the term used by Nodejs) an object that reference the methods defined in the module.

So for example, we will have a module named "baseObject" defined as follows :

var util = require('util');
var base = function() {}

base.prototype = {
	asString : function() {
		return util.inspect(this, true, null);
	}
}
module.exports = base;

 This module defined an object called base, that have a single method called "asString()" which simply dumps a string representation of the object using Nodejs "util.inspect" method , and we export this object .

And we have another object called "settings" that also needs to define a method "asString()" to dump the string representation of that object , defiantly the proper way to do this in Java is to have "settings" inherit from "base" , but how to do so in Nodejs , here is how :

var obj = require("./utils/objectUtils.js");// Defines "inherit" method
var base = require("./utils/baseObject.js");// Holds "asString()" method that we want "settings" to inherit it.
var settings = function() {
	this.x=1;
        this.y=2
}
// Inheirt from the base object 
obj.inherit(base,settings);
module.exports = new settings();

So what did we do is , before we export the module , we called the method "inherit" to copy the prototype of "base" class into "settings" class.

This will result having the following code simply works :

var settings=require('./settings.js');
console.log(settings.asString());

Reactions:

1 comments:

Anonymous said...

Thank you