Looking at different methods of how to find max/min values in Javascript Array I can often see extending prototype of Array object itself. So having:
var a=[22,33,44,32,1];
Array.max=function(v) {
return Math.max.apply(this,v);
};
Array.max(a); // returns 44
However I often do as below:
Array.prototype.max=function() {
return Math.max.apply(this,this);
};
a.max(); // returns 44
This allows me to call max() with no parameters on the Array object itself. Personally I don't see any problem with it and I keep wondering if am I missing something and this method has some major problems I overlook? Is it safe to use as Array.max(arrayhere)
?
EDIT: Is it correct to say that in first example we creating static method on native Javascript Array object and in second example we extending Arrays prototype?
Is it correct to say that in first example we creating static method on native Javascript Array object and in second example we extending Arrays prototype?
Yes.
Personally I don't see any problem with it and I keep wondering if am I missing something and this method has some major problems I overlook?
Some people who use for in
on arrays might trip over your enumerable max
method. While I personally think that they deserve it, one can play safe
Is it safe to use as
Array.max(arrayhere)
?
Yes, it avoids the enumerability concern. However, you still need to consider that extending javascript natives has its own problems, see also Why is extending native objects a bad practice?. If you chose the static approach anyway, putting them on your own library object instead doesn't complicate anything.