Previous
Function 
Next
Getting Information 
ABC of JavaScript : An Interactive JavaScript Tutorial
Object Oriented JavaScipt Programming

Object Oriented JavaScript

This is a tricky concept so I want your complete attention. This is the only part of JavaScript that I could not understand when I first studied JavaScript. At that time, I made JavaScript scripts without using a OO(Object Oriented) approach. But after I managed to study how to do OO programming in JavaScript, I could not believe how I managed to program before I learned it.

So if you don't understand this chapter, you can still program in JavaScript, but you will miss out on a much easier way to do it.

Constructor

The first thing to know about OO is the constructor. This will make the object. Remember how to create an Array?

var arr = new Array(5);

Here 'Array' is the name of the constructor and 5 is the argument that is given to the constructor. Making a constructor is same as creating a function. Let see how to create a constructor. First we need to know what object we are going to make. Let say that we need to create one about movies. We need the following information -
Movie title
Lead Actor
Plot
Tagline.

Let us create a constructor for this object.

function makeMovie(name,lead,plot,tagline) {
	this.title = name
	this.plot = plot
	this.actors = lead
	this.tag = tagline
	alert("Made new film called " + this.title)
}

Member variable

See the this.whatever line? That 'whatever' will be a member variable of the object that is made with the constructor. Now let us make a object with this constructor.

var movie = new makeMovie("Team America - World Police","Puppets",
"Marionette super heroes fight to end terrorism and put tired \
celebrities out of their misery.",
"Putting the 'F' back in Freedom.");

Never thought that it was this easy to make a movie, did you? Now let us see how to access the member variables in this object.

alert("Movie : "+movie.title+"\nTagline : "+movie.tag)

This will give an output

Movie : Team America - World Police
Tagline : Putting the 'F' back in Freedom.

The format of accessing an element is in this form.
<Name_of_Object>.<Name_of_element> - which in our case is
movie.title

Multiple Objects

Say that we need to create many movies - any successful producer would make multiple movies. So before proceeding any further, take a paper, write 'Producer' on it and stick it to the back of your chair.

One way is to give every movie variable unique names. Like this...

team_america = new makeMovie(...);
serendipity = new makeMovie(...);
etc.

But that is not the best way. So let us make an array and store all the movies in it.

var movies = new Array(5);
movies[0] = new makeMovie("Serendipity","John Cusak, Kate Beckensale",
"A couple reunite years after the night they first met, fell in love, \
and separated, convinced that one day they'd end up together.",
"Can Once In A Lifetime Happen Twice?")

movies[1] = new makeMovie("Ice Age","Rave Romano,Dennis Leary, John Cusamo",
"The Journey of three 'friends' to return a human kid to its herd when \
the next Iceage is just round the conner.",
"The story of four strangers who go from sub zero to heroes.")

movies[2] = new makeMovie("Spider Man","Tony Maguire",
"When bitten by a genetically modified spider, a high school student gains \
spider-like abilities which he uses to fight evil as a superhero.",
"With great power comes great responsibility.")

movies[3] = new makeMovie("Bruce Almighty","Jim Carrey, Morgan Freeman",
"A guy who complains about God too often is given almighty powers to teach him \
how difficult it is to run the world.","He's got the Power.")

movies[4] = new makeMovie("Meet The Parents","Ben Stiller, Robert DeNero",
"First comes love. Then comes the interrogation.",
"Male nurse Greg Focker meets his girlfriend's parents before proposing, but \
her suspicious father is every date's worst nightmare.")

alert(movies[3].actors+" where in film "+movies[3].title)

Alright! Now we are the producers of five films. And one more thing - if any of the actors names are spelled incorrectly, please forgive me. My spell checker would not know the correct spellings and I am too lazy to go on the net to find the correct spellings.

Member Functions

Now lets add a method(or functions, as some call them) to our class. Insert the following lines after the constructor definition.

//New method for the 'makeMovie' class
function showActors() {
	alert(this.actors + " are the main actors in "+ this.title);
}
//Set the method prototype
makeMovie.prototype.showActors = showActors;

Calling the new method is just as easy. Just use this format
<Object_name>.<Method_Name>()
Like this(insert this after all five movies are defined) -
movies[3].showActors()

We have created five objects of a class and storied it in an array. What more can a guy want? Now you can do whatever you want with this array - you can search it, you can sort it. You can add to it, you can remove from it. In short you can do any thing with it short of putting it on a lease and taking it for a walk.

You can try out what you learned here. Change stuff as your wish. Experiment with it.

Previous
Function 
Next
Getting Information 
blog comments powered by Disqus