Thursday 10 February 2011

Extending the JavaScript language

Something useful i found searching the internet is that you can extend existing JavaScript functions by using Extension methods. In this example an array class is extended with a contains-method:
Array.prototype.contains = function(value) {
for (var i = 0; i < this.length; i++)
if (this[i] == value) return true;
return false;
}
We can then use the extension method as follows
var myArray = ["a", "b", "c"];
myArray.contains("c"); // true

No comments:

Post a Comment