Monday, May 14, 2012

JavaScript Object Oriented Technique #0 Common Object Methods

Whenever we define a JavaScript class, there are three methods we should immediately define.

toString()

We should be able to return a string representation useful enough for debugging purposes.

We might want to consider adding a static parse() method to our class, parsing a string output from toString() back to object form.

The usual conventions, for objects, is to surround the string by brackets [...] and describe the object's properties within it.

Polygon.prototype.toString = function() {
    return "[Polygon with perimeter "+this.perimeter+", with area "
        + this.area+", centered at ("+this.x+", "+this.y+").]";
}

valueOf()

Typically, we write an valueOf() method to give us a number form of our object.

The textbook example is, since JavaScript number objects are supposedly "real" numbers, then for a complex number object the valueOf() should return the real part. Why? Because it lets us do the following:

var foo = new Complex(1,2);
var bar = new Complex(3,4);
var spam = Complex.sum(foo,bar); // spam is the complex number (4,6)
var eggs = foo + bar; // eggs is the number 4

Also note that the valueOf() method is called when concatenating a string with your object. So continuing from the previous example:

console.log("foo = " + foo); // uses valueOf(), displays "foo = 1"
console.log("foo = " + foo.toString()); // displays "foo = {1,2}"

You have been warned!

Comparison Methods

It's useful to sort objects, and creating comparison methods allows us to do this.

The first one we should consider is equals(), which tests if two objects are equal in some sense. Usually it's if the properties are the same.

Next we need to test for inequalities. We implement a compareTo() method, which should behave as follows:

foo.compareTo(bar)>0; // foo > bar
foo.compareTo(bar)==0; // foo == bar
foo.compareTo(bar)<0; // foo < bar

I suppose the best implementation might have the following skeleton:

MyClass.prototype.compareTo = function(that) {
    if(this.equals(that))
    {
        return 0;
    }
    // else return something like "this.valueOf() - that.valueOf()"
}

Again, it depends on the circumstances...

No comments: