Prototype attribute usage in JavaScript

Source: Internet
Author: User
Tags time interval

First, we need to understand the concept of the class, JavaScript itself is an object-oriented language, it involves elements depending on their attributes are attached to a particular class. 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 methods), such as array push method, date Get series method, String split method, and so on.

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:

1, the simplest example, understand prototype:
(1) Number.add (num): function, number added
Implementation method:

The code is as follows Copy Code
Number.prototype.add = function (num) {return (this+num);}

Test: Alert ((3). Add (->) display 18

(2) Boolean.rev (): function, Boolean variable reverse
Implementation method: Boolean.prototype.rev = function () {return (!this);}
Test: Alert ((True). Rev ())-> display false

Is it simple? This section is just a way of telling the reader that this is the way it is used.

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:

The code is as follows Copy Code
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:

The code is as follows Copy Code
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)

(2) String.Length
Function: This is actually an attribute of the String class, but since JavaScript treats both Full-width and Half-width as a single character, there may be a problem in some practical use, and now we are using prototype to make up for this deficiency.
Implementation method:

The code is as follows Copy Code
String.prototype.cnLength = function () {
var arr=this.match (/[^x00-xff]/ig);
Return this.length+ (arr==null?0:arr.length);
}

Test: Alert ("Easewe space Spaces". Cnlength ())-> display 16
Here we use some regular expression method and Full-width character coding principle, because belong to another two larger categories, this article does not add, please refer to the relevant materials.

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:

  code is as follows copy code
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 ("Easewe space Spaces". Left (8))-> Display Easewe space
Alert ("Easewe space Spaces". Left (8,true))-> shows Easewe empty
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:

The code is as follows Copy Code
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:

  code is as follows copy code
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!

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

Prototype property: Returns a reference to the object type prototype.
Objectname.prototype
The objectname parameter is the name of the object.

Use the prototype property to provide a set of basic functions for the object's class. The operation of the new instance of the object, "inherit", gives the object a prototype.
For example, to add a method that returns the maximum element value in an array for the array object. To do this, declare the function, add it to the Array.prototype, and use it.

The code is as follows Copy Code

function Array_max () {
var i, max = this[0];
for (i = 1; i < this.length; i++)
{
if (Max < this[i])
max = This[i];
}
return Max;
}
Array.prototype.max = Array_max; Join

var x = new Array (1, 2, 3, 4, 5, 6);
var y = X.max ();

After the code executes, Y saves the maximum value in the array x, or says 6.
All JScript internal objects have read-only prototype properties. You can add functionality to the prototype as in this example, but the object cannot be given a different prototype. However, user-defined objects can be assigned to a new prototype.

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.