Extension method equivalents in JavaScript

How to write an extension method for a type in JavaScript

  • Share

For someone who works in C#, extension methods are one really useful feature introduced in .NET framework.

I use extension methods a lot because they are so nicely integrated with intellisense and you can access them really easy.

Luckily for us, C# developers, they are available in JavaScript as well but they are a little bit different. in JavaScrpipt they can be implemented with prototype approach.

The prototype property allows you to add properties and methods to an object an because everything in JavaScript is derived from Object, you can create your own prototype behavior to pretty much anything in JavaScript. Very similar to C#.

The following methods TryParseInt is declared for String type and returns int value.

String.prototype.TryParseInt = function() {
     var result = 0;
     if(this !== null) {
         if(this.length > 0) {
             if (!isNaN(this)) {
                 result = parseInt(this);
             }
         }
     }
     return result;
}
    

The same way you can build up other methods for different types as well

String.prototype.TryParseFloat = function() {
     var result = 0;
     if(this !== null) {
         if(this.length > 0) {
             if (!isNaN(this)) {
                 result = parseFloat(this);
             }
         }
     }
     return result;
}

String.prototype.TryParseBool = function() {
     var result = false;
     if(this !== null) {
         if(this.length > 0) {
             if (!isNaN(this)) {
				 if(this.toLowerCase()=="true" || this.toLowerCase()=="yes" || this.toLowerCase()=="1"){
					result = true;
				 }
             }
         }
     }
     return result;
}
    
  • Share

Disclaimer

Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.

Comments for this article

comments powered by Disqus