Monday, 30 September 2013

Extending properties/methods of an existing class in JavaScript

In JavaScript, properties/methods of an existing class can be extended by using the 'prototype' property of that class. Let's see an example of how to add a function named 'isInt' to String class. This function, as is obvious from its name, tells whether the text content of the target String is a number or not.


<script>
if (String.prototype.isInt == null) {
String.prototype.isInt = function() {
var result = parseInt(this.valueOf());
return !isNaN(result);
}
}
var i = "27";
var j = "shyam";
var paraElement = document.getElementById("output");
paraElement.innerHTML = ("Is '27' an integer : " + i.isInt());
paraElement.innerHTML += (" <br > Is 'shyam' an integer : " + j.isInt());
</script>

2 comments: