Object Oriented JavaScript

Posted by Montu on December 10, 2008

Lately I have been studying Object Oriented Programming. I come from a background of small snippets, everything wrapped inside a small bulletproof function. Optimized to run as fast as possible. Things have changed from simple print function to more sophisticated print method or a system class (arghh!!!).
When I first wrote a piece of code for Linux I was told, everything is a file on a *nix system. So even if it is a directory/socket/drive/device you can treat it as a file and open it, read from it and write into it. So if you are going to do anything related to Linux tell yourself, everything is a file. Same in OOPS, tell your self everything is an object and it has some properties and some methods or in general have members. No functions. No variables. Everything is inherited or abstract or private or protected or…
JS, abbrevation for JavaScript, is an Object Based language totaly different from C, C++, Java or .NET and it is not truly Object Oriented. But still there are tweaks and hacks that allows one to model some concepts of OO. Object Based languages are also reffered as Prototype based languages. Prototypes as the word implies are not concrete objects and hence do not possess all the qualities, read methods and properties, of an object. Hence a string object in JavaScript may be or may not be same as string object in any other language.
All said and done. What all OO features can be implemented using JS?
a) we can define our own Objects.
b) we can extend predefined objects
c) we can inherit objects, really?? “Yes Sire”.
d) we can simulate classes, remember simulation is far away from reality.
Time to jump into code. Do it yourself.

/*
Just a quick hack ;-)
*/
function d(str){
	document.write(str);
}

{//Brace added just to limit everything in to local scope
/*
a constructor
*/
var bikeSimple = function(){ }
/*
Or
*/
function simpleBike(){ }

var pulsor = new bikeSimple;
var splendor = new simpleBike();

}//Brace added just to limit everything in to local scope

{//Brace added just to limit everything in to local scope
/*
Initialise an object
*/
/*
a constructor
*/
var bikeSimple = function(modelName, cc, mileage){
	/*
	Private members.
	*/
	var modelName = modelName;
	var cc = cc;
	var mileage = mileage;
	function canBeDriven(){
		return true;
	}
	/*
	Public members
	*/
	this.color = ‘Black’;
	/*
	*/
	this.sounds = function(){
		d(’Vroom!’);
	}
}
var pulsor = new bikeSimple(’Pulsor DTSi’, ‘150/180/220′, ‘40-50′);
/*
Or even the Object Initializer way.
*/
var cruiserBike = {modelName:’Bullet 350′, cc:’350′, mileage:’45-50′ }
}//Brace added just to limit everything in to local scope

{//Brace added just to limit everything in to local scope
/*
Set/Get/Delete properties using methods
*/
/*
a constructor
*/
var bike = function(){
	this.setInfo = function(modelName, cc, mileage){
		this.modelName = modelName;
		this.cc = cc;
		this.mileage = mileage;
	}
	this.getInfo = function(){
		d(’Model: ‘ + this.modelName + ‘CC: ‘ + this.cc + ‘Mileage:’ + this.mileage );
	}
	this.vroomProperty = ‘vroom!!!’;
	this.vroom = function(nTimes){
		nTimes = (nTimes < 0 ? 1 : nTimes);
		for(i=0;i
			d(this.modelName + ‘ says ‘ +this.vroomProperty);
		}
	}
}
/*
Sample (and simple too!) invocation
*/
var pulsor = new bike;
pulsor.setInfo(’Pulsor DTSi’, ‘150/180/220′, ‘40-50′);
pulsor.getInfo();
pulsor.vroom(5);
/*
Or even this also works, not the OO way to do things
*/
function cruiserBike(modelName, cc, mileage){
	this.setInfo = function(modelName, cc, mileage){
		this.modelName = modelName;
		this.cc = cc;
		this.mileage = mileage;
	}
}
var bullet = new cruiserBike;
bullet.setInfo(’Bullet 350+’, ‘350′, ‘40-45′);
bullet.getInfo = function(){
		d(’Model: ‘ + this.modelName + ‘CC: ‘ + this.cc + ‘Mileage:’ + this.mileage);
	}
bullet.getInfo();
/*
But wait…
*/
var thunderbird = new cruiserBike;
thunderbird.setInfo(’Thunderbird’, ‘350′, ‘40-45′);
/*
This will throw an error
thunderbird.getInfo();
*/
/*
That vroom property is stupid, delete the property.
*/
delete pulsor.vroomProperty;
pulsor.vroom(5);
/*
Can I do this?
Apparently not this way.
*/
delete pulsor.vroom();
pulsor.vroom(3);

/*
…but this way, look no parenthesis
*/
delete pulsor.vroom;
pulsor.vroom(3);

/*
And the Object Initializer way. This led to JSON.
*/
var ducatiMatrix = {setInfo: function(modelName, cc, mileage){
		this.modelName = modelName;
		this.cc = cc;
		this.mileage = mileage;
	},
	getInfo:function(){
			d(’Model: ‘ + this.modelName + ‘CC: ‘ + this.cc + ‘Mileage:’ + this.mileage);
		}
	}
ducatiMatrix.getInfo();
}//Brace added just to limit everything in to local scope

{//Brace added just to limit everything in to local scope
/*
The power of prototyping
*/
/*
a constructor
*/
var bike = function(){}
bike.prototype.setInfo = function(modelName, cc, mileage){
	this.modelName = modelName;
	this.cc = cc;
	this.mileage = mileage;
}
bike.prototype.getInfo = function(){
	d(’Model: ‘ + this.modelName + ‘CC: ‘ + this.cc + ‘Mileage:’ + this.mileage );
}
/*
Sample (and simple too!) invocation, again!
*/
var pulsor = new bike;
pulsor.setInfo(’Pulsor DTSi’, ‘150/180/220′, ‘40-50′);
pulsor.getInfo();
/*
…& the following
*/
Date.prototype.myBirthDay = function(){
	return(’My birthday falls on 3rd December, you can gift me iPods, Zunes, Toughbook, high speed data line..’);
}
/*
Chainining the object, and look the Date is a native object and I haveadded my own method to it!
*/
d((new Date).myBirthDay());
}//Brace added just to limit everything in to local scope
 
 
Trackbacks

Use this link to trackback from your own site.

Comments

Leave a response

  1. Adnan Wed, 10 Dec 2008 15:36:41 PST


    Date.prototype.myBirthDay

    you can extend extending objects by same method. For instance you can do something like:


    String.prototype.trim

    and later can use your own trim function for any string operation.

  2. Vinish Wed, 10 Dec 2008 15:57:02 PST

    Don’t trust when a technical writer suggests something in a code… but you missed something critical in the code :).

    There is no exception-handling (//comment) that says ‘technical writers - try at your own risk…’ :)

  3. Sukhbir Wed, 10 Dec 2008 16:29:48 PST

    Dude. Lots of people will disagree with you, specially college freshers. You are ACTUALLY using OOP where you can avoid it! Ha haa!

  4. Sukhbir Wed, 10 Dec 2008 16:30:50 PST

    And why the hell is your blog timezone in EST? Use IST man!

  5. Kumar Chetan Sharma Wed, 10 Dec 2008 16:36:56 PST

    @Vinish: This is just an experiment.
    @Sukhi bhaji: You are missing THE point, OO is in fashion, OO is hot :P, and its really advisable to use OO features in JS

  6. Adnan Wed, 10 Dec 2008 16:44:50 PST

    yeah fashion. OO lala!!

  7. Montu Wed, 10 Dec 2008 16:45:47 PST

    @Daddu: Dude, thats what I am trying to tell by extending Date object, you can extend any object. Extend, i.e. add, its not advisable to tinker with existing methods or property.

  8. Montu Wed, 10 Dec 2008 22:17:03 PST

    @Sukhi Bhaaji: IST done! Thanks for pointing :-)

Comments


Fine Print: In very short I own my views & if you don't like something on my blog, I am sorry, I can't help you. In fact I am not even sorry. Ch33r5.