[Translation] how to extend the JavaScript function-JavaScript Weekly Guide [Phase 3]

Source: Internet
Author: User

In the morning, I saw the article "javascript Weekly Guide" [Phase 3], which contains an articleArticle(Extending JavaScript-the right way), I think it is not bad. I will share the translation with you. This article is not translated word by word and should be as easy as possible.

Original article address: extending JavaScript-the right way

The following is a translation

Javascript already has many powerful built-in methods, but sometimes you don't need a function in the built-in method. How can we elegantly extend the JavaScript function.

For example, we want to add a capitalize () method to enable uppercase of the first letter. We usually write it like this:

 
If(!String. Prototype. capitalize) {string. Prototype. capitalize=Function(){Return This. Slice (0, 1). touppercase () +This. Slice (1). Tolowercase ();}}

The aboveCodeIt can be used normally, but if there is the following code somewhere:

VaRStrings = "yay";For(IInStrings) console. Log (I + ":" + strings [I]);

The result is as follows:

 
0: Y1:2: Ycapitalize:Function(){Return This. Slice (0, 1). touppercase () +This. Slice (1). tolowercase ();}

This is obviously not the expected result. The reason why we added the method is that we added the method.The default value of the enumerable attribute is true.

We can simply set the enumerable to false to avoid this problem, and use the defineproperty Method for Function Extension:

If(!String. Prototype. capitalize) {object. defineproperty (string. prototype,'Capitalize', {Value:Function(){Return This. Slice (0, 1). touppercase () +This. Slice (1). Tolowercase () ;}, enumerable:False});}

Now run the following code:

 
VaRStrings = "yay";For(IInStrings) console. Log (I + ":" + strings [I]);

The result is:

0: Y1:2: Y

It should be noted that if no loop is output, it does not mean that the loop does not exist. We can view the definition through the following code:

 
VaRStrings = "yay"; Console. Log (strings. capitalize)

Output:

 
Function(){Return This. Slice (0, 1). touppercase () +This. Slice (1). tolowercase ();}

You can use this method to extend the JavaScript function flexibly.To define our own objects and set some default values.

 

The following are several other extension methods that you can use in your project:

String. pxtoint ()

Convert a string like "200px" to a number 200:

If(!String. Prototype. pxtoint) {object. defineproperty (string. prototype,'Pxtoint', {Value:Function(){ReturnParseint (This. Split ('px ') [0]);}, Enumerable:False});}

 

String. ishex ()

Determines whether a string is in hexadecimal format, for example, "# CCC" or "# cacaca"

If(!String. Prototype. ishex) {object. defineproperty (string. prototype,'Ishex', {Value:Function(){Return This. Substring (0, 1) = '#'&&(This. Length = 4 |This. Length = 7) & amp;/^ [0-9a-fa-f] + $/. Test (This. Slice (1);}, Enumerable:False});}

 

String. Reverse ()

String inversion:

 
If(!String. Prototype. Reverse) {object. defineproperty (string. prototype,'Reverse', {Value:Function(){Return This. Split (''). Reverse (). Join ('') ;}, Enumerable:False});}

 

String. wordcount ()

Count the number of words, separated by Spaces

 
If(!String. Prototype. wordcount) {object. defineproperty (string. prototype,'Wordcount', {Value:Function(){Return This. Split (''). Length ;}, enumerable:False});}

 

String.html entities ()

HTML tags, such as <and>, are encoded as special characters.

 
If(!String.prototype.html entities) {object. defineproperty (string. prototype,'Htmlentities', {Value:Function(){ReturnString (This). Replace (// G, '&'). Replace (//G, '>'). Replace (/"/g ,'"');}, Enumerable:False});}

 

String. striptags ()

Remove HTML tags:

 
If(!String. Prototype. striptags) {object. defineproperty (string. prototype,'Striptags', {Value:Function(){Return This. Replace (/<\/? [^>] +>/GI ,'') ;}, Enumerable:False});}

 

String. Trim ()

Remove spaces at the beginning and end:

 
If(!String. Prototype. Trim) {object. defineproperty (string. prototype,'Trim', {Value:Function(){Return This. Replace (/^ \ s */, ""). Replace (/\ s * $ /,"") ;}, Enumerable:False});}

 

String. stripnonalpha ()

Remove non-letter characters:

 
If(!String. Prototype. stripnonalpha) {object. defineproperty (string. prototype,'Stripnonalpha', {Value:Function(){Return This. Replace (/[^ A-Za-Z] +/g ,"") ;}, Enumerable:False});}

 

Object. sizeof ()

Statistics object size, such as {one:" and ", two: "and"} is 2

If(!Object. Prototype. sizeof) {object. defineproperty (object. prototype,'SIZE', {Value:Function(){VaRCounter = 0;For(IndexIn This) Counter ++;ReturnCounter;}, enumerable:False});}
PS

In this way, the functions of JS native objects are quite good, but unless necessary (many objects are used in the project), it is not recommended to extend the functions directly on the native object, which will causeGlobal variable pollution.

In addition, the pxtoint () method in this article is unnecessary. In JS, parseint () can directly complete this function: parsetint ("200px") = 200

The htmlentities method seems to be faulty. Another one is provided below:

 If (! String.prototype.html entities) {object. defineproperty (string. prototype, 'Htmlentities' , {Value:  Function  (){  VaR DIV = Document. createelement ("Div" );  If  (Div. textcontent) {Div. textcontent = This ;}  Else  {Div. innertext = This  ;}  Return  Div. innerhtml;}, enumerable:  False  });} 

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.