Modify Object
1. Create a New Method
Part of JavaScript fun is creating your own method. You can use it for some common operations. Improve efficiency (human flesh efficiency,ProgramEfficiency .....).
Consider the following example:
1 VaRInum = 10;
2Inum = inum. tostring (16 );
3Alert (inum );//Output ""
Here we use the tostrong method of the number object to convert inum to hexadecimal characters. if we need to perform frequent operations on such numbers. for example, color data operations. you can create a new method in this way.
Rewrite the example above:
1Number. Prototype. tohexstring =Function(){
2Return This. Tostring (16 );//This always points to the object that calls this method.
3}
4 VaRInum = 10;
5Alert (inum. tohexstring ());//Output ""
At the same time, you can reverse write a hexadecimal character to a decimal number. Create the following method:
1String. Prototype. hextodecimal =Function(){
2ReturnParseint (This, 16 );
3}
4
5 VaRSnum = "1f ";
6Alert (snum. hextodecimal ());//Output 31
In this way, you can define your own methods.
You can also add some local objects with some existing methods. String has the indexof method, but the array does not. Then we can add consistent methods.
Example:
1Array. Prototype. indexof =Function(Sitem ){
2For(VaRIIn This){
3If(Sitem =This[I])ReturnI;
4}
5};
6 VaRAtest = ["A", "B", "C"];
7Alert (Atest. indexof ("B "));
If you want to add the same method to each local object, you can define
1Object. Prototype. sayvalue =Function(){
2Alert (This. Valueof ());
3};
4 VaRSshow = "Bay ";
5 VaRInum = 88;
6Sshow. sayvalue ();//Output "Bay"
7Inum. sayvalue ();//Output "88"
2. Redefinition of existing methods
Of course, you can also overwrite the original method,
1 function. prototype. tostring = function () {
2 return " is nothing "
3 };
4 function sayhello () {
5 alert (" hello ");
6 }< br> 7 alert (sayhello. tostring ();