使用apply与函数构造函数

Geo*_*uer 5 javascript

可能重复:
将.apply()与'new'运算符一起使用.这可能吗?

我有5或6个表单的变量赋值

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');
Run Code Online (Sandbox Code Playgroud)

如您所见,这些构造函数的很大一部分非常相似.如果我可以创建一个小的通用currying构建器,这将允许我做类似的事情将是很好的:

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');
Run Code Online (Sandbox Code Playgroud)

我可以用类似的东西来实现

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

但严重ick.我希望能够将前三个已知参数拼接到arguments数组的开头并将其应用于FuncDef但是我被需要使用new运算符所挫败.

在有人要求之前,我不能在FuncDef中执行新的操作符强制,因为它是由coffeescript类关键字生成的.

use*_*621 3

当然可以。这是一种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(',') + ')');
}
Run Code Online (Sandbox Code Playgroud)

(从另一个线程盗来的)