Javascript prototype attributes and modification objects

Source: Internet
Author: User

Javascript prototype attributes

 

Definition and usage

The prototype attribute enables you to add attributes and methods to an object.

 

Syntax

Object. Prototype. Name = Value

 

Instance

In this example, we will show how to use the prototype attribute to add attributes to an object:

 
<SCRIPT type = "text/JavaScript"> function employee (name, job, born) {This. name = Name; this. job = job; this. born = born;} var bill = new employee ("Bill Gates", "engineer", 1985 );Employee. Prototype. Salary = NULL;Bill. Salary = 20000;Document. Write (Bill. Salary); </SCRIPT>

Output:

20000

 

========================================================== ==========================================================

 

Modify JavaScript prototype object

 

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.

Create a New Method(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" indicates the instance of the number.Therefore, you can fully access all methods of number. With this sectionCodeTo 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 ".

 

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 (){ReturnThis. Shift ();};

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"

Add new methods for local objects

Finally, if you wantAdd a new method for each local object,It must be defined 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 ".

Redefinition of existing methods

Just like defining new methods for existing classes, you can also redefine existing methods. As described in the previous chapter,The function name is just a pointer to the function.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 still remember that the tostring () method of function is usually output by function in the function object chapter.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 unitsProgramRecycle because it is completely discarded. 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.

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.

 

 

reprinted statement: This article is transferred from http://www.w3school.com.cn/js/pro_js_object_modifying.asp

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.