I’m creating a small code plugin which allows you to do some things with arrays. I do not wish to add the functions to the array object using a prototype construction, what I want is that people can do something like:
arrayFunction( [1, 2, 3] ).someSpecialArrayFunction();
Thus leaving the normal array object unaltered.
So I came up with the following construction (which was inspired on the jQuery source code) :
var arrayFunction = window.arrayFunction = function(array) { return new arrayFunction.fn.init(array); } arrayFunction.fn = arrayFunction.prototype = { init: function(array){ this.a = array; //should I return something here? }, someSpecialArrayFunction: function(){ //Super cool custom stuff here. } }
However this does not work (obviously). What should happen in the init function()?
The error right now is that when I try:
arrayFunction(array).someSpecialArrayFunction();
it says that someSpecialArrayFunction() is not a function?
How should one do this?
edit
Yes, this is indeed a simpliefied example. The actual thing has way more methods.
Also, I just though of how awesome it would be if it also supported chaning, how would you do that?
Or simply:
Although be careful with this, if you end up with too many methods It’s probably better to use the prototype.