Article

JavaScript Object-Oriented Programming Part 2

Page: 1 2 3 4 Next

Prototype

Every object constructor has a special property, prototype. This property allows you to add properties/methods to all objects created from that object constructor. Sound confusing? It's not. Let's look at some examples:

function Square(){  
}  
var squareObj = new Square();  
Square.prototype.side = 5;  
var squareObj2 = new Square();  
alert(squareObj.side); // displays 5  
alert(squareObj2.side); // displays 5

What this does is add a side property, with an initial value of 5, to all Square objects, whether they've been created, or have yet to be created. The prototype object (it is, in fact, an object) loads before the object constructor does anything. So, this code:

function Square(){  
 this.side=5;  
}  
var squareObj = new Square();  
Square.prototype.side = 4;  
var squareObj2 = new Square();  
alert(squareObj.side); // displays 5  
alert(squareObj2.side); // displays 5

returns 5, because everything in the prototype object loads first (before the Square() object constructor even runs), so the properties and methods defined in the constructor will override it. So, with the prototype property, you can't override any properties or methods defined in an object's constructor (the function that creates the object). Using the String's prototype property, we can add new methods to String objects. Consider this example:

function consonantize(){  
 var consonants ="";  
 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" && l!="  
"){  
     consonants+=l;  
   }  
 }  
 return consonants;  
}

The above function goes through a string and removes all vowels and spaces, returning only consonants. Now, we can use it on any String object, or any String primitive datum:

String.prototype.consonantize = consonantize;  
var dg = "Danny Goodman";  
var df = new String("David Flanagan");  
alert(dg.consonantize());  
alert(df.consonantize());

Neat, huh? Note how the new method, just like other String methods, can be used by a String object or by a String primitive data type. Therefore, by using an object constructor's prototype method, we can add properties and methods to both native objects and user-defined objects.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links