I discussed the basics of Object Oriented Javascript Programming in my previous post. Now lets extend a class to add some more properties and methods to its definition.
Every object constructor has a special property ‘prototype’ in Javascript (Please do not confuse it with prototype javascript library). Lets use it:
function myClass() {
}
myClass.prototype.aProperty = "foo";
var myObject = new myClass();
alert(myObject.aProperty);
This adds aProperty to the definition of myClass. The ‘prototype’ adds this property to all the objects whether they have been created or not. So, this example will work too:
function myClass() {
}
var myObject = new myClass();
myClass.prototype.aProperty = "foo";
alert(myObject.aProperty);
The ‘prototype’ object loads before the object’s constructor does anything.
function myClass() {
this.aProperty = "bar";
}
var myObject = new myClass();
myClass.prototype.aProperty = "foo";
alert(myObject.aProperty);
// this alert will show "bar"
So, using ‘prototype’ we cannot override the properties and methods already defined in the object’s constructor.
We can use the ‘prototype’ to add functionalities to the already existing classes. Lets add some functionality to the String class.
String.prototype.vowelLength = function() {
var count = 0;
for(i=0; i < this.length; i++) {
var l = this.charAt(i);
if(l == "a" || l == "A" || l == "e" || l == "E" || l == "i" || l == "I" || l == "o" || l == "O" || l == "u" || l == "U") {
count++;
}
}
return count;
}
var myString = "United States of America";
alert(myString.vowelLength());


