The correct way to extend JavaScript functionality (translation) _javascript tips

Source: Internet
Author: User
Tags trim

In the morning to see the "JavaScript Weekly Guide" "Phase III" of the article, which found an article (extending javascript–the right Way), feel good, translated to share with you, this article is not a word for translation, as far as possible to speak in plain language.

Original address: extending Javascript–the right Way

The following is the translation

JavaScript already has a lot of powerful methods built into it, but sometimes you need a feature that isn't in the built-in method, so how do we extend the JavaScript functionality gracefully?
For example, we would like to add a capitalize () method to capitalize the first letter, which we usually write:

Copy Code code as follows:

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

The code above works fine, but if you have the following code somewhere:
Copy Code code as follows:

var strings = "Yay";
For (I in Strings) Console.log (i + ":" + strings[i]);

And the result we've got is this:
0:y
1:a
2:y
Capitalize:function () {return This.slice (0, 1). toUpperCase () + this.slice (1). toLowerCase ();
This is obviously not the result we want, and the reason we have the added method is that the enumerable property of our added method defaults to True.
We can do this by simply setting the enumeration property (enumerable) to false to avoid this problem by using the DefineProperty method to extend the function:
Copy Code code 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 we're going to run this piece of code:
Copy Code code as follows:

var strings = "Yay";
For (I in Strings) Console.log (i + ":" + strings[i]);

The results we get are:
0:y
1:a
2:y
It should be noted that the loop without output does not mean that it does not exist, and we can see the definition in the following code:
Copy Code code as follows:

var strings = "Yay";
Console.log (Strings.capitalize)

Will output:
Copy Code code as follows:

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

Extending the JavaScript functionality in this way is more flexible, and we can define our own objects in this way and set some default values.
Here are a couple of other extension methods that you can use in your own project:
String.pxtoint ()
Converts a string such as "200px" to the number 200:
Copy Code code 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 a 16-binary representation, such as "#CCC" or "#CACACA"
Copy Code code 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 Code code 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 Code code as follows:

if (! String.prototype.wordCount)
{
Object.defineproperty (String.prototype, ' WordCount ',
{
Value:function ()
{
return This.split ('). length;
},
Enumerable:false
});
}

String.htmlentities ()
HTML tags such as < and > encoded as special characters
Copy Code code as follows:

if (! String.prototype.htmlEntities)
{
Object.defineproperty (String.prototype, ' htmlentities ',
{
Value:function ()
{
Return String (this). Replace (/&/g, ' & '). Replace (//g, ' > '). Replace (/"/g, '");
},
Enumerable:false
});
}

String.striptags ()
Remove HTML Tags:
Copy Code code as follows:

if (! String.prototype.stripTags)
{
Object.defineproperty (String.prototype, ' striptags ',
{
Value:function ()
{
Return This.replace (/<\/?[ ^>]+>/gi, "");
},
Enumerable:false
});
}

String.Trim ()
Remove the trailing space:
Copy Code code 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-alphabetic characters:
Copy Code code as follows:

if (! String.prototype.stripNonAlpha)
{
Object.defineproperty (String.prototype, ' Stripnonalpha ',
{
Value:function ()
{
Return This.replace (/[^a-za-z]+/g, "");
},
Enumerable:false
});
}

Object.sizeof ()
Statistics the size of the object, such as {one: "and", Two: "and"} is 2
Copy Code code as follows:

if (! Object.prototype.sizeof)
{
Object.defineproperty (Object.prototype, ' sizeof ',
{
Value:function ()
{
var counter = 0;
For (index in this) counter++;
return counter;
},
Enumerable:false
});
}


This way to extend the function of JS native object is quite good, but unless necessary (a lot of project use), do not recommend directly on the original object to extend the function, will cause global variable pollution.
In addition, the text of the Pxtoint () method is not necessary, JS parseint () can directly complete such a function: Parsetint ("200px") ===200
There appears to be a problem with the Htmlentities method, which provides another:
Copy Code code as follows:

if (! String.prototype.htmlEntities)
{
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
});
}

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.