0

I want to write a function like this:

function myNew(constructor) {
    return constructor.applyNew(Array.prototype.slice.call(arguments, 1));
}

Only applyNew doesn't exist. Is there a way around this?

user2864740
  • 60,010
  • 15
  • 145
  • 220
  • 2
    What is `applyNew`? What are you trying to do? – putvande Jan 22 '14 at 23:59
  • @putvande A hypothetical combination of `new` + `Function.prototype.apply` – user2864740 Jan 22 '14 at 23:59
  • @PatrickEvans How? It should have `new` semantics *and* perform application is in `apply`. – user2864740 Jan 23 '14 at 00:00
  • Consider defining the "`applyNew`" semantics better - in case they aren't what I'm championing ;-) - and removing the `myNew` context which doesn't seem relevant. – user2864740 Jan 23 '14 at 00:02
  • So is this right: you want to call some function using `new` but send in a variable number of arguments? It is hard to tell because of the way you use `arguments` in your example. – Ray Toal Jan 23 '14 at 00:04

2 Answers2

3

You first have to create an object that inherits from the constructor function's prototype, and then apply the constructor function to that object to initialize it:

function applyNew(fn, args) {
    var obj;
    obj = Object.create(fn.prototype);
    fn.apply(obj, args);
    return obj;
}
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
  • Definitely seems like a legit way to do it in ES5+ (the linked/duplicate question has a number of ES3 answers). – user2864740 Jan 23 '14 at 00:07
  • +1 Wouldn't it be handy to have an operator so you could just do `foo fn(args)`. Oh wait, there is one. It's called *new*. :-) – RobG Jan 23 '14 at 00:11
  • @RobG, assuming the constructor is set up to accept an array instead of a series of arguments, which is not always possible. Generally speaking, `new` should be preferred when possible. – zzzzBov Jan 23 '14 at 00:15
0

Edited (I didn't think about the array before):

function myNew(constructor) {
    var args = arguments;
    function F() {
        return constructor.apply(this, Array.prototype.slice.call(args, 1));
    }
    F.prototype = constructor.prototype;
    return new F();
}
Kenneth
  • 28,294
  • 6
  • 61
  • 84