Description of properties of JavaScript prototype objects _javascript tips

Source: Internet
Author: User
Tags add numbers time interval

One, what is the prototype property of the object in JavaScript
JavaScript, the prototype property of the object that is used to return the reference to the object type prototype. We use the prototype property to provide a set of basic functions for the object's class. And a new instance of the object "inherits" the action given to the object's prototype. But how exactly is this prototype implemented and managed?
for the description of the object's prototype property, the JavaScript manual says: All JavaScript internal objects have read-only prototype properties. You can dynamically add functionality (properties and methods) to its prototype, but the object cannot be assigned a different prototype. However, user-defined objects can be assigned to a new prototype.

in JavaScript, the prototype object is an important mechanism for implementing object-oriented objects. Each function is an object (function) that has a child object prototype object, and the class is defined as a function. Prototype represents the prototype of the function and also represents a collection of members of a class. When you create an instance object of a class by using new, the members of the prototype object become members of the instantiated object.
1, the object is referenced by the class, only the function object can be referenced;
2, after the new instantiation, its members are instantiated and the instance object can be invoked.
Also, a function is an object that can be invoked if a function object declares a member directly without being instantiated.
JavaScript supports inheritance through a linkage mechanism, rather than through a class-based inheritance model that is supported by fully object-oriented languages such as Java. Each JavaScript object has a built-in attribute named prototype. The prototype property holds a reference to another JavaScript object that acts as the parent object of the current object. &NBSP

When a function or property of an object is referenced by a dot notation, the object's prototype property is used when the function or property is not on the object. When this occurs, the object prototype property is checked to see if there are any requested properties or functions. If the object referenced by the prototype property does not also have the required function or property, the prototype property of the object (the object referenced by the prototype property) is further examined, followed by the chain up, until the requested function or property is found, or the end of the chain is reached. Returns undefined if it has not been found at the end of the chain. In this sense, this kind of inheritance structure should be more a "has a" relationship than "is a" relationship
God, I can understand anything. Seems to make me very cow, to tell the truth I also can not understand! ^_^ ^_^ ^_^
Two, prototype attribute application example
Our common classes include: array variables (arrays), logical variables (Boolean), date variables (date), struct variables (Function), numeric variables (number), object variables (objects), string variables (string), and so on. The related class methods are often used by programmers (here to distinguish between class attention and attribute hair method), such as array push method, date Get series method, String split method, etc.
But in the actual programming process do not know that there is no sense of the existing methods of deficiencies? Prototype method came into being! Below, through the example to explain the specific use of prototype:
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
First create a Func object, set the Name property of the Func object, and instantiate the F;

1. A few simple examples:
(1) Add numbers:
JavaScript code
Number.prototype.add=function (num) {
Return (This+num)//This point to number
};
Alert ((3). Add (15));//18
(2) Boolean.rev (): function, Boolean variable reverse
Implementation method: Boolean.prototype.rev = function () {return (!this);}
Test: Alert ((True). Rev ())-> display false
2, the existing methods of implementation and enhancement, the first knowledge of prototype:
(1) Array.push (new_element)
Function: 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 strengthen him so that he can add multiple elements at once!
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;
}
Not ugly, you know? And so on, you can think about how to do this by enhancing array.pop to remove any number of elements (the code is no longer detailed)

3, the implementation of new functions, in-depth prototype: In the actual programming used in the affirmation is not only the enhancement of the existing methods, more implementation of the function requirements, I will give two to solve the actual problem with prototype examples:
(1) String.left ()
Problem: The use of VB should know the left function, from the left-hand side of the string to take n characters, but the problem is that the full angle, half angle is considered a character, resulting in a mixed in Chinese and English layout can not intercept such a long string
function: intercept n characters from the left side of the string and support the distinction of full-width 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))-> show AA
Alert ("AA la AA". Left (4,true))-> show AA
This method uses the above mentioned String.tlength () method, the custom method also can combine some good new method!
(2) Date.daydiff ()
Action: Calculates the time interval (year, month, Day, week) of two date-type 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 (2002,0,1)))-> display 329
Alert (new Date ()). Daydiff (New Date (2002,0,1)), "M")-> display 10
Of course, it can be further expanded to get the response hours, minutes, or even seconds.
(3) Number.fact ()
Function: factorial of a 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 ())-> display 24
This method is mainly to illustrate the recursive method in the prototype method is also feasible!
Instance:
To take the maximum value of an array:
JavaScript code
var oarr=new Array ();
OARR=[100,190,199,189,3000,400,4001];
Array.prototype.max=function () {
var i,max=this[0];
for (i=1;i<this.length;i++) {
if (Max<this[i]) {
Max=this[i];
}
}
return Max;
}
Alert (Oarr.max ());
Instance to add a method to a user-defined 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 ();
It is said that this is the inheritance of the wrong saying; Oh, I'll learn it later.
One more example, I guess you and I are 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");
};
Following execution
RP = new RP ();
Alert (RP. Propertya);//The warning result is: 1
Rp. The MethodA ()///warning result is: Rp.methoda
Alert (Rp. Propertya);//The warning result is: 100
Rp. MethodA ();//The result of the warning is: this. MethodA
Delete RP. Propertya;
Alert (RP. Propertya);//The result of the warning is: undefined

Delete Rp. Propertya;
Alert (Rp. Propertya);//The warning result is: 100
Delete Rp. MethodA;
Rp. The MethodA ()///warning result is: RP.prototype.MethodA
Look at an area with a parameter that calculates the circle:

JavaScript code
<script type= "Text/javascript" >
function Circle (x,y,r) {
this.x = x;
This.y = y;
THIS.R = R;
This.prototype = null; /* This code can be seen as implied, because the definition of "class" in JavaScript and the definition of functions are not different, so it can be said that all functions hide such a property. */
}
Circle.prototype.area=function () {
return this.r*this.r*3.1415926;
}
var circ=new Circle (0,0,5);
Alert (parseint (Circ.area ()));
</script>

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.