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