If you are trying to replicate a method that is defined for some browsers but not others, try to get the definition to match the native implementation.
if(![].indexOf){
Array.prototype.indexOf= function indexOf(what, i){
i= i || 0;
var L= this.length;
while(i< L){
if(this[i]=== what) return i;
++i;
}
return -1;
}
}
if(![].map){
Array.prototype.map= function map(fun, scope){
var L= this.length, A= Array(this.length), i= 0, val;
if(typeof fun== 'function'){
while(i< L){
if(i in this){
A[i]= fun.call(scope, this[i], i, this);
}
++i;
}
return A;
}
else throw 'missing function argument';
}
}
if(!''.trim){
String.prototype.trim= function trim(){
return this.replace(/^\s+|\s+$/g,'');
}
}
The native method will be used, if possible.
If you roll your own methods, try to give them a name that isn't likely to be pre-empted
I like to have a shuffle and a naturalSort method for arrays,
but I give them slightly off beat names.
Array.prototype.a1Sort= function(){
var a, b, a1, b1, rx= /(\d+)|(\D+)/g, rd= /\d+/;
return this.sort(function(as, bs){
a= String(as).toLowerCase().match(rx);
b= String(bs).toLowerCase().match(rx);
while(a.length && b.length){
a1= a.shift();
b1= b.shift();
if(rd.test(a1) || rd.test(b1)){
if(!rd.test(a1)) return 1;
if(!rd.test(b1)) return -1;
if(a1!= b1) return a1 - b1;
}
else if(a1!= b1) return a1> b1? 1: -1;
}
return a.length - b.length;
});
}
Array.prototype.disorder= function(force){
var i, temp, L= this.length, A= force? this: this.concat();
while(--L){
i= Math.floor(Math.random()*L);
temp= A[i];
A[i]= A[L];
A[L]= temp;
}
return A;
}
If you do add to the prototypes, make sure you document it and reference the doc in every script that uses them-
if anyone is ever going to work with your code, including you.