Usage of prototype in Javascript

Source: Internet
Author: User

This article introduces how to use prototype attributes in Javascript. This article is applicable to beginners. I hope to help you all.

First, we need to first understand the concept of a class. JavaScript itself is an object-oriented language, and its elements depend on a specific class according to different attributes. 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 differentiate the class attention and attribute sending methods), such as the push method of the array, the get method of the date series, the split method of the string, and so on.

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:

1. The simplest example is prototype:
(1) Number. add (num): function, Number Addition
Implementation Method:

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

Test: alert (3). add (15)-> show 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

Is it easy? This section only tells readers that this method is used in this way.

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:

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

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;
}

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)

(2) String. length
Purpose: this is actually an attribute of the String class. However, JavaScript regards full and half-width as a character, which may cause some problems in some practical applications, now we use 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 ()-> show 16
Here we use some regular expression methods and full-byte character encoding principles. because they belong to the other two relatively large classes, this article does not describe them. Please refer to the relevant materials.

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:

The 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)-> show EaseWe empty
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:

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 (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:

The 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 ()-> 24
This method mainly demonstrates that the recursive method is also feasible in the prototype method!

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

Prototype attribute: return the reference of the Object Type prototype.
ObjectName. prototype
The objectName parameter is the object name.

The prototype attribute provides a set of basic functions of the object class. The new instance of the object "inherits" the operation that is granted to the object prototype.
For example, you want to add a method to the Array object to return the maximum element value in the Array. To accomplish this, declare the function, add it to 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; // Add

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

After the code is executed, y saves the maximum value in array x, or 6.
All internal JScript objects have the read-only prototype attribute. You can add features for the prototype as in this example, but the object cannot be assigned different prototypes. However, user-defined objects can be assigned to new prototypes.

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.