OO advanced options in JavaScript – part III

In the previous posts, we’ve started looking at several important details associated with “emulating” classical OO programming in JavaScript. Today we’ll keep looking at this pattern and we’ll see how we can emulate method overloading. Before going on, I’d like to make a point about the “abuse” you’ll be seeing in the following snippet.  As I’ve said before, there are much better ways of doing OO programming in JavaScript.

Having said this, I believe that seeing all the work needed for emulating this kind of stuff will, for instance, contribute for having a better opinion on platforms like MS ASP.NET AJAX library, which let you use classical OO paradigms with JavaScript.

Since I don’t really have much time, we’ll go directly to the code. The idea is simple: we’ll reuse the last post hierarchy and we’ll change the printInfo method so that it returns a string with the “contents” of the current object:

var Person = function(name) {
    this.name = name;
}
Person.prototype.printInfo = function() {
    return this.name;
}
var Student = function(name, age) {
    //simulate base initialization
    Person.apply(this, [name]);
    this.age = age;
}
Student.prototype = new Person();
Student.prototype.printInfo = function() {
    var baseMethod = Person.prototype["printInfo"];
    var baseResult = baseMethod.call(this);
    return baseResult + "-" + this.age;
}
Student.prototype.constructor = Student;//update constructor
var newPerson = new Person("luis");
var newStudent = new Student("john", 20);
alert(newStudent.printInfo());

As you can see,we’re “overwriting” the printInfo method on the Student class. We’re doing this because the inherited base method won’t return the complete info for each Student instance. I guess that in this simple example it would be really simple to just concatenate name and age and return that. However,I wanted to show you how you could reuse the returned value from the base class’ method and that’s why I opted for using the call method (notice that I’ve chosen to use the call method because the base method didn’t expect any parameters).

And that’s it for this post. Keep tuned for more on JavaScript.

Advertisements

~ by Luis Abreu on September 7, 2009.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: