) Javascript: Prototype attribute usage instructions

Source: Internet
Author: User

From: http://bokee.shinylife.net/blog/article.asp? Id = 455

Prototype is a method introduced in IE 4 and later versions for a certain type of objects, and it is particularly convenient: it is a method for adding methods to class objects! This may sound a little messy. Don't worry. I will explain this special method through the example below:

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 so on.ProgramFrequently Used by members (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:

1. The simplest example is prototype:
(1) number. Add (Num): function, Number Addition
Implementation Method: 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. 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;
}< br> Let's further enhance it so that it can add multiple elements at a time!
Implementation Method:
array. prototype. pushpro = function () {
var currentlength = This. length;
for (VAR I = 0; I This [currentlength + I] = arguments [I];
}< br> return this. length;
}< br> isn't it easy to understand? And so on, you can consider how to enhance array. pop to delete any location and any number of elements (the specific Code is not described in detail)

(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:
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:
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 );
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:
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;
Case "M ":
Result/= base * 365/12;
Case "W ":
Result/= base * 7;
Result/= base;
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;
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!

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.