0

I am working on a project that has a collection object that can create item objects. The item object also create and special handler object. When the user creates the collection object they can define the default handler object the item objects will generate and what arguments that handler can take.

I have found the task of moving and storing a reference to an Object prototype and subsequent constructor arguments a bit messy. This is what I have so far:

function Handler( val ) {

    console.log( val );

}

function Collection( handlerArray ) {

    this.handler = handlerArray;

}
Collection.prototype.addItem = function() {

    new Item( this.handler );

};

function Item( handlerArray ) {

    handlerRef = handlerArray.shift();
    handlerArgs = handlerArray;

    HandlerApply = function( args ) {
        return handlerRef.apply( this, args );
    };
    HandlerApply.prototype = Handler.prototype;

    new HandlerApply( handlerArgs );

}

myCollection = new Collection( [
    Handler,
    'Hello'
] );

myCollection.addItem();

Is there a more elegant solution to passing object prototypes and constructor arguments?

Thanks

McShaman
  • 3,627
  • 8
  • 33
  • 46
  • 1
    I usually pass one object argument to a chain of functions such as constructor or mediator and let the individual functions take, add or mutate wherever member of that object applies to them. An example can be found here.http://stackoverflow.com/questions/16063394/prototypical-inheritance-writing-up/16063711#16063711 under passing (constructor) arguments – HMR Apr 06 '14 at 13:56

1 Answers1

0

I have invented a fairly elegant solution. An object that I call an install object. Its an object that takes a reference to an constructor and then the arguments that will be used with that constructor. This object can be stored and passed around and then with the run function can instantiate the stored object.

function objectInstaller( ref ) {

    this.ref = ref;
    this.args = Array.prototype.slice.call( arguments, 1 );

}

objectInstaller.prototype.run = function() {

    function Apply( ref, args ) {

        return ref.apply( this, args );

    }
    Apply.prototype = this.ref.prototype;

    return( new Apply( this.ref, this.args ) );

};

function MyObject( val ) {

    console.log( val );

}

var myInstall = new objectInstaller( MyObject, 'hello' );

var myObject = myInstall.run();
McShaman
  • 3,627
  • 8
  • 33
  • 46