In this post, I will show how to use this unique inheritance feature of Javascript, aka prototypal inheritance, to customize built in Javascript objects like arrays. Particularly, I will show how to add a custom method to the Javascript Array object so that any array you use in your javascript app can use that method.
Whenever you create a new array in Javascript, it is an object inheriting from the Array object. Our target is to add a search method to the Array object. Wouldn’t it be convenient to be able to search arrays like
var result = myArray.find("Mango"); Well, wouldn’t it?
You bet it will be. But Javascript arrays do not come with a find method. Let us put it into the Array object so that all arrays can use it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | Array.prototype.find = function(key, value) { var i; if(!key && !value) { return this; //return the whole array since no parameters are passed } for(i = 0; i < this.length; i++) { if(!value) { //if only one parameter is passed, it will be found as key, value will be null value = key; if(this[i] == value) return this[i]; } else { if(this[i][key] == value) return this[i]; } } return null; } |
The use of the keyword prototype in the function declaration makes this function available to all sub-objects of Array, i.e. all arrays in your Javascript app. In the same way, you could add a variable to Array. And you can put any object before the prototype keyword. That is the beauty of Javascript’s prototypal inheritance; the hierarchy can start from anywhere.
If you have ever worked with ArrayLists or Vectors in C# or Java (these are expandable arrays, for those who do not know), you will have noticed that ArrayList or Vector class comes in with lots and lots of helper methods like toString(), find() for manipulating the arrays. Javascript does not give you so many helper methods built-in. But using prototypal inheritance, you can very easilly add helper methods like these and make your arrays more fun to use.
No comments:
Post a Comment