Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use apply with a function constructor [duplicate]

Tags:

javascript

Possible Duplicate:
Use of .apply() with 'new' operator. Is this possible?

I have 5 or 6 variable assignments of the form

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 amount of portion of these constructors are very much alike. It would be nice if I could create a little generic currying 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 like to just be able to splice the first three known parameters to the beginning of the arguments array and apply it to the FuncDef but I'm being foiled by the need to use the new operator.

And before someone asks, I can't do new-operator enforcement inside of FuncDef because it's being generated by the coffeescript class keyword.

like image 810
George Mauer Avatar asked Oct 05 '11 20:10

George Mauer


1 Answers

Of course it can be done. This is the one case where eval turns out to be useful.

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(',') + ')');
}

(stolen from another thread)

like image 90
user123444555621 Avatar answered Sep 30 '22 08:09

user123444555621