Javascript Object modification method

Source: Internet
Author: User

1. Create a New Method

Use the Prototype attribute to define new methods for any existing class, just like processing your own class. For example, do you still remember the tostring () method of the Number class? If 16 is passed, it will output a hexadecimal string. Isn't it better to use the toHexstring () method to process this operation? It is easy to create:

Number.prototype.toHexstring = function(){   return this.toString(16);}    

In this environment, the keyword "this" points to the instance of Number, so you can fully access all methods of Number. With this code, you can perform the following operations:

var iNum = 15;alert(iNum.toHexstring());  //outputs "F" 

 

Ii. Redefinition of existing methods

Just like defining new methods for existing classes, you can also redefine existing methods. The function name is just a pointer to the function, because it can easily point to other functions. What happens if you modify the local method, such as toString?

 

Function.prototype.toString = function () {  return "Function code hidden";} 

The preceding code is completely legal and the running result is exactly as expected:

 

function sayHi(){  alert("hi");} alert(sayHi.tostring());  //outputs "Function code hidden" 

Sometimes you may even call the original method in the new method:

 

Function.prototype.originalToString = Function.prototype.toString; Function.prototype.toString = Function(){  if(this.originalToString().length>100){     return "Function too long to display." }else{     return this.originalToString();  }};

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.