Introduction to modifying objects using javascript_ecmascript

Source: Internet
Author: User
Document directory
  • (1) create a new method using an existing Method
  • (2) Rename an existing Method
  • (3) add methods irrelevant to existing methods
  • (4) Add a new method for the local object

Preface:By using ecmascript, you can not only create objects, but also modify the behavior of existing objects. The prototype attribute can not only define the attributes and methods of the constructor, but also add attributes and methods for local objects.

1. Create a New Method (1) create a new method using an existing Method

You can 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 parameter 16 is passed to it, It outputs a hexadecimal string. If the parameter of this method is 2, it will output a binary string. You can create a method to convert a numeric object to a hexadecimal string. This method is very simple:

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 (); // output "F"

The warning is displayed because the number 15 is equal to the value F in hexadecimal notation ".

(2) Rename an existing Method

We can also name existing methods more easily. For example, you can add two methods enqueue () and dequeue () to the array class, just let them repeatedly call the existing push () and shift () methods:

Array.prototype.enqueue = function(vItem) {  this.push(vItem);};Array.prototype.dequeue = function() {  return this.shift();};
(3) add methods irrelevant to existing methods

Of course, you can also add methods irrelevant to existing methods. For example, if you want to determine the position of an item in the array, there is no local method to do this. We can easily create the following method:

Array.prototype.indexOf = function (vItem) {  for (var i=0; i<this.length; i++) {    if (vItem == this[i]) {  return i;}  }  return -1;}

The method indexof () is consistent with the method of the same name as the string class, and each item is retrieved in the array until the same project as the Imported item is found. If the same item is found, the position of the item is returned. Otherwise,-1 is returned. With this definition, we can write the following code:

VaR acolors = new array ("red", "green", "blue"); alert (acolors. indexof ("green"); // output "1"
(4) Add a new method for the local object

Finally, to add a new method to each local object in ecmascript, you must define it on the prototype attribute of the object. As we have mentioned in the previous chapter, all local objects inherit the object, so any changes to the object will be reflected on all local objects. For example, if you want to add a method that uses the current value of the warning output object, you can use the following code:

Object. prototype. showvalue = function () {alert (this. valueof () ;}; var STR = "hello"; var inum = 25; Str. showvalue (); // output "hello" inum. showvalue (); // output "25"

Here, both string and number objects inherit the showvalue () method from the object and call this method on their objects respectively. "hello" and "25" are displayed ".

Ii. Redefinition of existing methods

Just like defining new methods for existing classes, you can also redefine existing methods. As described in the previous section, function names only point to function pointers, so you 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 (); // output "function code hidden"

You may remember that the function object chapter describes the function's tostring () method, which usually outputs the function's source code. Overwrite this method and return another string (in this example, you can return "function code hidden "). However, what happened to the original function pointed to by tostring? It will be recycled by useless storage unit recycler because it is completely deprecated. There is no way to restore the original function, so before overwriting the original method, it is safer to store its pointer for future use. 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();  }};

In this Code, the first line of code saves the reference to the current tostring () method in the originaltostring attribute. The custom method overwrites the tostring () method. The new method checks whether the source code length of the function is greater than 100. If yes, an error message is returned, indicating that the function code is too long. Otherwise, the originaltostring () method is called to return the source code of the function.

3. Very late binding (very late binding)

Technically speaking, there is no very late binding at all. This term is used in this book to describe a phenomenon in ecmascript, that is, the method that can be defined after an object is instantiated. For example:

var o = new Object();Object.prototype.sayHi = function () {  alert("hi");};o.sayHi();

In most programming languages, the object method must be defined before the object is instantiated. Here, the method sayhi () is added after an instance of the object class is created. In traditional languages, you have not heard of this operation, nor have you heard of this method. It also automatically assigns the instance of the object to be used immediately (the next line ).

Note:It is not recommended to use the late binding method because it is difficult to track and record it. However, we should still understand this possibility.

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.