Prototype is a really efficient way of extending an object or class and I have found numerous uses of this over the years, getting to know the way prototype works will greatly improve your ability to develop javascript, you will eventualy create your own tools using prototype.
The code below is an extension of the array object, using prototype, it allows a function to remove duplicates from an array, pretty basic but has been useful for me in the past and will hopefully show you the potential this could have for your developing. Enough words, show me the example.
Example of Prototype
The Code (in use):
awl.prototypeExample = new (function(){
/* PUBLIC */
this.init = function (){
//extend Array object to remove duplicate entries
Array.prototype.removeDuplicates = function() {
var nArray = [];
for (i=0; i<this.length; i++) {
//if its not already in the new array add it
if(!nArray.hasValue(this[i])) {
nArray.push(this[i]);
}
}
return nArray;
}
//prototype to check if in array
Array.prototype.hasValue = function(value) {
var i;
for (i=0; i<this.length; i++) {
if (this[i] === value) return true;
}
return false;
}
//USING THE NEW PROTOTYPE METHOD
jQuery("#cleanDuplicates").click(function(e){
//get array string
var aTemp = jQuery("#duplicates").val();
//split array
aTemp = aTemp.split(",");
//remove the Dupes
aTemp = aTemp.removeDuplicates();
//clear old results
jQuery("#duplicateClean").html("");
//now place the new array on screen for user
for (i=0; i<aTemp.length; i++) {
var delimiter = (i==0) ? '<strong>The Resulting Array:</strong>
' : ',';
jQuery("#duplicateClean").append(delimiter+aTemp[i]);
}
return false;
});
}
});
Leave A Comment