Use with constructor functions

Possible duplicate:
Using .apply () with the 'new' operator. Is it possible?

I have 5 or 6 form variable assignments

var analyteSelection = new TemplatedSelectionContainer($('.analyte-container', this), helpers, optionsTemplate);
var instrumentSelection = new AssetBackedSelection($('.instrument-container', this), helpers, optionsTemplate, Assets.instruments, 'Instrument');
var methodSelection = new AssetBackedSelection($('.method-container', this), helpers, optionsTemplate, Assets.methods, 'Method');

As you can see, a significant portion of these constructors are very similar. It would be nice if I could create a small pedigree curry builder that would allow me to do something like:

var newSel = selectionContainerBuilder(this, helpers, optionsTemplate)
var analyteSelection = newSel(TemplatedSelectionContainer, '.analyte-container');
var instrumentSelection = newSel(AssetBackedSelection, '.instrument-container', Assets.instruments, 'Instrument');
var methodSelection = newSel(AssetBackedSelection, '.method-container', Assets.methods, 'Method');

I can achieve something similar with

var selectionContainerBuilder = function(ctx, helpers, optionsTemplate) {
  return function(FuncDef, selector, a, b, c, d, e, f) {
    return new FuncDef($(selector, ctx), helpers, optionsTemplate, a,b,c,d,e,f);
  }
}

But seriously ick. I would just like to associate the first three known parameters with the beginning of an array of arguments and apply it to FuncDef, but I don't like using the new operator.

And before someone asks, I cannot force the execution of a new statement inside FuncDef because it is generated by the keyword of the coffeescript class.

+5
2

, . , eval .

function newApply(cls, args) {
    var argsAsString = [];
    for (var i = 0, l = args.length; i < l; i++) {
        argsAsString.push('args[' + i + ']');
    }
    return eval('new cls(' + argsAsString.join(',') + ')');
}

( )

+3

! Javascript, , , 1.

(, ), / 2 .


1 "..." Harmony ( JS), .

2 , . (, ).

new Foo("arg1", {
    helpers: helpers,
    options: optionsTemplate,
    intruments:  Assets.instruments
});

: : .apply() 'new'. ?

+2

All Articles