JavaScriptprototype object attribute description_javascript skills

Source: Internet
Author: User
The prototype attribute of the object in JavaScript is used to return the reference of the Object Type prototype. We use the prototype attribute to provide a set of basic functions of the object class. In addition, the new instance "inherit" of the object grants the operation of the object prototype. But how is this prototype implemented and managed? 1. What is the prototype attribute of objects in JavaScript?
The prototype attribute of the object in JavaScript is used to return the reference of the Object Type prototype. We use the prototype attribute to provide a set of basic functions of the object class. In addition, the new instance "inherit" of the object grants the operation of the object prototype. But how is this prototype implemented and managed?
For the description of the prototype attribute of an object, the JavaScript manual says: All JavaScript internal objects have the read-only prototype attribute. You can dynamically add features (attributes and methods) to the prototype, but the object cannot be assigned different prototypes. However, user-defined objects can be assigned to new prototypes.

In JavaScript, prototype objects are an important mechanism for implementing object-oriented. Each Function is an object (Function). The Function object has a prototype object and the class is defined as a Function. Prototype indicates the prototype of the function and a set of class members. When a class instance object is created through new, all members of the prototype object become members of the instantiated object.
1. This object is referenced by the class and can only be referenced by function objects;
2. After the new instance is instantiated, its members are instantiated and the instance object can be called.
At the same time, a function is an object. If a function object directly declares a member, it can be called without being instantiated.
JavaScript supports inheritance through a link mechanism, rather than the class-based inheritance model supported by fully object-oriented languages (such as Java. Each JavaScript Object has a built-in property named prototype. The prototype property stores a reference to another JavaScript Object, which serves as the parent object of the current object.
 

When a function or attribute of an object is referenced by the vertex method, if the object does not have this function or attribute, the prototype attribute of the object is used. In this case, the system checks the object referenced by the prototype attribute of the object to check whether any Requested attribute or function is available. If no function or attribute is required for the object referenced by the prototype attribute, the prototype attribute of this object (the object referenced by the prototype attribute) will be further checked and searched up along the chain in sequence, until the requested function or attribute is found, or the end of the chain is reached. If the end of the chain is not found, undefined is returned. In this sense, this inheritance structure should be a "has a" relationship, rather than a "is a" relationship.
God, I understand everything. What should I do? It seems that I am a good guy. To tell the truth, I cannot understand it! Pai_^
Ii. prototype attribute application instance
Common classes include: Array, Boolean, Date, Function, and Number), Object, String, and other related class methods, it is also frequently used by programmers (here we need to distinguish between class attention and attribute sending methods), such as the push method of the array, the get method of the date series, and the split method of the string,
But in the actual programming process, I wonder if I feel the shortcomings of the existing method? The prototype method came into being! The following describes how to use prototype in a simple way:
Let's look at a silly example:

JavaScript code
Function func (){
Func. prototype. name = "prototype of func ";
}
Var f = new func ();
Alert (f. name); // prototype of func
Create a func object, set the name attribute of the func object, and instantiate f;

1. A few simple examples:
(1) number addition:
JavaScript code
Number. prototype. add = function (num ){
Return (this + num); // here this points to Number
};
Alert (3). add (15); // 18
(2) Boolean. rev (): returns the inverse of a Boolean variable.
Implementation Method: Boolean. prototype. rev = function () {return (! This );}
Test: alert (true). rev ()-> show false
2. Implementation and enhancement of existing methods:
(1) Array. push (new_element)
Purpose: Add a new element to the end of the array.
Implementation Method:
Array. prototype. push = function (new_element ){
This [this. length] = new_element;
Return this. length;
}
Let's further enhance him so that he can add multiple elements at a time!
Implementation Method:
Array. prototype. pushPro = function (){
Var currentLength = this. length;
For (var I = 0; I <arguments. length; I ++ ){
This [currentLength + I] = arguments [I];
}
Return this. length;
}
Should it be difficult to understand? Similarly, you can consider how to delete any location and multiple elements by enhancing Array. pop (the specific code will not be detailed)

3. Implementation of new functions, in-depth prototype: in actual programming, it is certainly not only the enhancement of existing methods, but also more functional requirements, here are two examples of solving the actual problem using prototype:
(1) String. left ()
Problem: Anyone who has used vb should know the left function and take n characters from the left of the string. However, the full and half-width characters are considered as one character, this makes it impossible to intercept long strings in a mix of Chinese and English la S.
Purpose: truncates n characters from the left side of the string and supports full-width and half-width characters.
Implementation Method:
String. prototype. left = function (num, mode ){
If (! /\ D +/. test (num) return (this );
Var str = this. substr (0, num );
If (! Mode) return str;
Var n = str. Tlength ()-str. length;
Num = num-parseInt (n/2 );
Return this. substr (0, num );
}
Test: alert ("aa la aa". left (4)-> display aa la
Alert ("aa la aa". left (4, true)-> display aa
This method uses the String. Tlength () method mentioned above, and some good new methods can be combined between custom methods!
(2) Date. DayDiff ()
Function: Calculate the interval (year, month, day, week) between two date variables)
Implementation Method:
Date. prototype. DayDiff = function (cDate, mode ){
Try {
CDate. getYear ();
} Catch (e ){
Return (0 );
}
Var base = 60*60*24*1000;
Var result = Math. abs (this-cDate );
Switch (mode ){
Case "y ":
Result/= base * 365;
Break;
Case "m ":
Result/= base * 365/12;
Break;
Case "w ":
Result/= base * 7;
Break;
Default:
Result/= base;
Break;
}
Return (Math. floor (result ));
}
Test: alert (new Date (). DayDiff (new Date (329, 1)-> show
Alert (new Date (). DayDiff (new Date (, 1), "m")-> show 10
Of course, it can be further expanded to get the response hour, minute, or even second.
(3) Number. fact ()
Role: factorial of a certain number
Implementation Method:
Number. prototype. fact = function (){
Var num = Math. floor (this );
If (num <0) return NaN;
If (num = 0 | num = 1)
Return 1;
Else
Return (num * (num-1). fact ());
}
Test: alert (4). fact ()-> 24
This method mainly demonstrates that the recursive method is also feasible in the prototype method!
Instance:
Take the maximum value of the array:
JavaScript code
Var oArr = new Array ();
OArr = [100,190,199,189,300, 4001,];
Array. prototype. MAX = function (){
Var I, max = this [0];
For (I = 1; I If (max Max = this [I];
}
}
Return max;
}
Alert (oArr. MAX ());
How to add an instance to a custom class:
JavaScript code
Function TestObject ()
{
This. m_Name = "ffffffffff ";
}

TestObject. prototype. ShowName = function ()
{
Alert (this. m_Name );
};
Var f = new TestObject ();
F. ShowName ();
Update the prototype of the custom class:

JavaScript code
Function TestObjectA ()
{
This. MethodA = function ()
{
Alert ('testobjecta. MethodA ()');
}
}

Function TestObjectB ()
{
This. MethodB = function ()
{
Alert ('testobjectb. MethodB ()');
}
}

TestObjectB. prototype = new TestObjectA ();
I heard that this is an inheritance in the wrong saying; I will learn it later.
Let's look at another example. I guess you and I are all crazy:

JavaScript code
Function RP ()
{
RP. PropertyA = 1;
RP. MethodA = function ()
{
Alert ("RP. MethodA ");
};

This. PropertyA = 100;
This. MethodA = function ()
{
Alert ("this. MethodA ");
};
}

RP. prototype. PropertyA = 10;
RP. prototype. MethodA = function ()
{
Alert ("RP. prototype. MethodA ");
};
// Run the following command:
Rp = new RP ();
Alert (RP. PropertyA); // warning result: 1
RP. MethodA (); // warning result: RP. MethodA
Alert (rp. PropertyA); // warning result: 100
Rp. MethodA (); // The warning result is: this. MethodA
Delete RP. PropertyA;
Alert (RP. PropertyA); // warning result: undefined

Delete rp. PropertyA;
Alert (rp. PropertyA); // warning result: 100
Delete rp. MethodA;
Rp. MethodA (); // warning result: RP. prototype. MethodA
Let's look at a parameter to calculate the area of the circle:

JavaScript code

Related Article

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.