A prototype is a good thing. Generally, the object prototype should not be extended. adding a new method to the prototype is a good choice.
Let's take a look at how to get the maximum and minimum values for the array. The most stupid method is estimated to be like this:
01.
Array. Prototype. max =
Function
(){
02.
VaR
Max =
This
[0];
03.
VaR
Len =
This
. Length;
04.
For
(
VaR
I = 1; I <Len; I ++ ){
05.
If
(
This
[I]> MAX ){
06.
Max =
This
[I];
07.
}
08.
}
09.
Return
Max;
10.
}
11.
Array. Prototype. min =
Function
(){
12.
VaR
Min =
This
[0];
13.
VaR
Len =
This
. Length;
14.
For
(
VaR
I = 1; I <Len; I ++ ){
15.
If
(
This
[I] <min ){
16.
Min =
This
[I];
17.
}
18.
}
19.
Return
Min;
20.
}
If you are introducing a class library for work and are afraid that the class library has also implemented a prototype method of the same name, we can judge before the generation:
1.
If
(
Typeof
Array. Prototype [
'Max'
] =
'Undefined'
){
2.
Array. Prototype. max =
Function
(){
3.
*************
4.
}
5.
}
But are these two extensions actually not very good ?! What native methods can be used for us? John resig cleverly uses the apply method to call native math. Max and math. Min methods to quickly obtain results. Apply allows a method to specify the call object and input parameters, and the input parameters are organized in arrays. It is precisely now that there is a method called math. Max, the calling object is math, and multiple parameters.
1.
Array. max =
Function
(Array ){
2.
Return
Math. Max. Apply (Math, array );
3.
};
4.
5.
Array. min =
Function
(Array ){
6.
Return
Math. Min. Apply (Math, array );
7.
};
However, John resig is a static method that makes them Math objects. It cannot be called using a chain that is a favorite of great gods. However, this method can be more streamlined. Don't forget that the math object is also an object. We can use the literal number of objects to write it, saving several bits.
1.
Array. Prototype. max =
Function
(){
2.
Return
Math. Max. Apply ({},
This
)
3.
}
4.
Array. Prototype. min =
Function
(){
5.
Return
Math. Min. Apply ({},
This
)
6.
}
1.
[1, 2, 3]. Max ()
// => 3
2.
[1, 2, 3]. Min ()
// => 1