Extend Native Objects

by Mohan 2012-09-20 22:30:50


Extend Native Objects
Even though some JavaScript gurus do not recommend this technique, it has been used by some frameworks. It allows you to create some helper methods, to the JavaScript API.
//We create the method prototype for our arrays
//It only sums numeric elements

Array.prototype.sum = function(){
var len = this.length;
total = 0;
for(var i=0;i<len ;i++){
if(typeof this[i]!= 'number') continue;
total += this[i];
}
return total;
}

var myArray = [1,2,3,'hola'];
myArray.sum();




Array.prototype.max = function(){
return Math.max.apply('',this);
}








768
like
0
dislike
0
mail
flag

You must LOGIN to add comments