The correct method for extending JavaScript Functions)

Source: Internet
Author: User

In The morning, I saw The article "JavaScript Weekly Guide" [Phase 3], in which I found an article (Extending JavaScript-The Right Way). I think it is not bad. I will share it with you through translation, this document is not translated word by word. It should be easy to understand.

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:
Copy codeThe 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:
Copy codeThe 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:
Copy codeThe 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:
Copy codeThe 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:
Copy codeThe Code is as follows:
Var strings = "yay ";
Console. log (strings. capitalize)

Output:
Copy codeThe 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:
Copy codeThe 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"
Copy codeThe 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:
Copy codeThe 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
Copy codeThe 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 as <and>, are encoded as special characters.
Copy codeThe 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:
Copy codeThe 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:
Copy codeThe 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:
Copy codeThe 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.
Copy codeThe 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:
Copy codeThe Code is as follows:
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.