Extension Methods in Javascript.

Can we create Extension Methods in Javascript?

One of the biggest development boosts is having a decent boilerplate code base you can use when starting new projects. One way to encourage re-use of code is the use of .NET extension methods. I like them so much, me and Fons Sonnemans made a website dedicated to them. My favorite methods are Chris Meijers IsFilled() and IsEmpty(). I use them all the time to avoid checking for !String.IsNullOrEmpty() which is a lot harder to read.

I am currently working on a HTML5 website that uses KnockoutJS, jQuery and a bit of MVC3 and need to check if a string has a value. I know Javascript should just support:

if (value) {
// you are here if value != null and value.length>0
}

but for some reason it did not work for me in combination with a Knockout Observable so I created a function that returns true when the string is filled. Then I wondered if Javascript has support for extension methods. And it has!

Javascript Extension Methods

The following code is a js file (/ExtensionMethods/String.js) that you can include in your project:

String.prototype.IsFilled = function () {
if (this && this.length > 0) {
return true;
}
return false;
}

String.prototype.IsEmpty = function () {
return !this.IsFilled();
}
Include and use the extensionmethod like this:
<!DOCTYPE html>
<html>
<head>
<title>Javascript ExtensionMethods</title>
<script src="Extensionmethods/String.js"></script>
<script type="text/javascript">
//<![CDATA[
var name="Loek van den Ouweland";
document.write("name.IsFilled(): "+name.IsFilled());
document.write("<br/>");
document.write("name.IsEmpty(): "+name.IsEmpty());
//```>
</script>
</head>
<body>
<h1>ExtensionMethods in Javascript</h1>
<h2><a href="http://loekvandenouweland.com/">http://loekvandenouweland.com/</a></h2>
</body>
</html>
Written by Loek van den Ouweland on 2012-05-15. Questions regarding this artice? You can send them to the address below.