I have created a JavaScript application that has a lot of array manipulations (sorting, filtering, etc.).
Currently my functions are like this:
function (myArray, arg1, arg2,...)
where myArray is the array I am working on, and arg1, arg2,… are the arguments used by the function to modify the array.
I am thinking that it would be neater to have a clear separation between the object and the arguments (a la jQuery):
myArray.function(arg1, arg2,...)
I know that I could use Array.prototype to add my function to all arrays, but this seems too heavy as the functions I add are really specific to my case and don’t make sense on arrays in general. I also know that I could create an object, but then I wouldn’t benefit from the array methods available in JavaScript (indexOf, filter, etc.).
Is there a way I could create my own array object, that would inherit the default array methods and allow me to add my own?
You’ve got two options:
Option one is to extend the
Arrayobject by adding new methods to it:The advantage is that every javascript array will now have this extra method. This can also be a disadvantage when multiple (external) javascript libraries try to add the same methods. Furthermore, this new method will appear in
for(var item in myArray)constructs which can be problematic.Option two is to create a “factory method” for your extended array:
Now you can write this to create a new extended array: