How to extend the JavaScript function? _ javascript tips-js tutorial

Source: Internet
Author: User
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 expand The JavaScript function? In The morning, I saw The article Extending JavaScript-The Right Way, the translation is shared with everyone. 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:

The Code is as follows:


If (! String. prototype. capitalize)
{
String. prototype. capitalize = function ()
{
Return this. slice (0, 1). toUpperCase () + this. slice (1). toLowerCase ();
}
}


The code above can be used normally, but if the code below exists somewhere:

The Code is as follows:


Var strings = "yay ";
For (I in strings) console. log (I + ":" + strings [I]);


The result is as follows:
0: y
1:
2: y
Capitalize: function () {return this. slice (0, 1). toUpperCase () + this. slice (1). toLowerCase ();}
This is obviously not the expected result. The reason for outputting the method we added is that the enumerable attribute of the method we added is true by default.
We can simply set the enumerable to false to avoid this problem, and use the defineProperty Method for Function Extension:

The Code is as follows:


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:

The Code is as follows:


Var strings = "yay ";
For (I in strings) console. log (I + ":" + strings [I]);


The result is:
0: y
1:
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:

The Code is as follows:


Var strings = "yay ";
Console. log (strings. capitalize)


Output:

The Code is as follows:


Function () {return this. slice (0, 1). toUpperCase () + this. slice (1). toLowerCase ();}


This method is more flexible to expand JavaScript Functions. We can use this method 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:

The Code is as follows:


If (! String. prototype. pxToInt)
{
Object. defineProperty (String. prototype, 'pxtoint ',
{
Value: function ()
{
Return parseInt (this. split ('px ') [0]);
},
Enumerable: false
});
}


String. isHex ()
Determines whether a string is in hexadecimal format, for example, "# CCC" or "# CACACA"

The Code is as follows:


If (! String. prototype. isHex)
{
Object. defineProperty (String. prototype, 'ishex ',
{
Value: function ()
{
Return this. substring (0, 1) = '#'&&
(This. length = 4 | this. length = 7 )&&
/^ [0-9a-fA-F] + $/. test (this. slice (1 ));
},
Enumerable: false
});
}


String. reverse ()
String inversion:

The Code is as follows:


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

The Code is as follows:


If (! String. prototype. wordCount)
{
Object. defineProperty (String. prototype, 'wordcount ',
{
Value: function ()
{
Return this. split (''). length;
},
Enumerable: false
});
}


String.html Entities ()
Html tags such <和> Encoded as special characters

The Code is as follows:


If (! String.prototype.html Entities)
{
Object. defineProperty (String. prototype, 'htmlentities ',
{
Value: function ()
{
Return String (this ). replace (// g ,'&'). replace (// g, '> '). replace (/"/g ,'"');
},
Enumerable: false
});
}


String. stripTags ()
Remove HTML tags:

The Code is as follows:


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:

The Code is as follows:


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:

The Code is as follows:


If (! String. prototype. stripNonAlpha)
{
Object. defineProperty (String. prototype, 'stripnonalpha ',
{
Value: function ()
{
Return this. replace (/[^ A-Za-z] +/g ,"");
},
Enumerable: false
});
}


Object. sizeof ()
The size of the statistical object, for example, {one: "and", two: "and"} is 2.

The Code is as follows:


If (! Object. prototype. sizeof)
{
Object. defineProperty (Object. prototype, 'SIZE ',
{
Value: function ()
{
Var counter = 0;
For (index in this) counter ++;
Return counter;
},
Enumerable: false
});
}



In this way, the native object function of JS is quite good, but unless necessary (many objects are used in the project), it is not recommended to extend the function directly on the native object, which will cause global 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:

The Code is as follows:


If (! String.prototype.html Entities)
{
Object. defineProperty (String. prototype, 'htmlentities ',
{
Value: function ()
{
Var p = document. createElement ("p ");
If (p. textContent ){
P. textContent = this;
}
Else {
P. innerText = this;
}
Return p. 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.