Basic JavaScript Object definition class or object (2)

Source: Internet
Author: User

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 ();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.