The concrete use method of prototype

Source: Internet
Author: User
Tags regular expression time interval

Prototype is a method for a class of objects introduced in IE 4 and later versions, and the special place is: it is a way to add a method to the object of the Class! This may sound a bit messy, don't worry, I will use the example to explain this particular method:

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 method), such as array push method, date Get series method, String split method, etc.

However, in the actual programming process do not know whether there is a lack of sense of the existing methods? The prototype method came into being! Below, will explain the concrete use method of prototype through the instance:

1, the simplest example, understand prototype:

(1) Number.add (num): function, number added

Implementation method:

01.number.prototype.add = function (num) {return (this+num);}

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

(2) Boolean.rev (): function, Boolean variable reverse

Implementation method:

01.boolean.prototype.rev = function () {return (!this);}

Test: Alert ((True). Rev ())-> display false

Is it simple? This section is simply 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:

01.array.prototype.push = function (new_element) {

This[this.length]=new_element;

return this.length;

04.}

Let's further strengthen him so that he can add multiple elements at once!

Implementation method:

01.array.prototype.pushpro = function () {

var currentlength = this.length;

for (var i = 0; i < arguments.length; i++) {

This[currentlength + i] = arguments[i];

05.}

This.length return;

07.

08.}

It's not ugly, you know? And so on, you can think about how to do this by enhancing array.pop to delete 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:

01.string.prototype.cnlength = function () {

var arr=this.match (/[^x00-xff]/ig);

Return this.length+ (arr==null?0:arr.length);

04.}

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:

01.string.prototype.left = function (Num,mode) {

if (!/d+/.test (num)) return (this);

var str = THIS.SUBSTR (0,num);

An. if (!mode) return str;

var n = str. Tlength ()-str.length;

num = Num-parseint (N/2);

Return This.substr (0,num);

08.}

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:

01.date.prototype.daydiff = function (Cdate,mode) {

02.try{

03.cdate.getyear ();

04.}catch (e) {

05.return (0);

06.}

07.var base =60*60*24*1000;

08.var result = Math.Abs (this-cdate);

09.switch (mode) {

10.case "Y":

11.result/=base*365;

12.break;

13.case "M":

14.RESULT/=BASE*365/12;

15.break;

16.case "W":

17.result/=base*7;

18.break;

19.default:

20.result/=base;

21.break;

22.}

23.return (Math.floor (result));

24.}

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:

01.number.prototype.fact=function () {

02.var num = Math.floor (this);

03.if (num<0) return NaN;

04.if (num==0 | | num==1)

05.return 1;

06.else

07.return (num* (num-1). fact ());

08.}

Test: Alert ((4). Fact ())-> display 24

This method is mainly to illustrate the recursive method in the prototype method is also feasible!

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.