2

I understand how Function.prototype.bind.apply works. Suppose the following definitions:

var Constructor = function(someArgument){
    //constructor body here
};

var creator = function(ctor, args){
    args.unshift(null); //or anything else to make 'bind' succeed
    return new (Function.prototype.bind.apply(ctor, args));
};

var creator2 = function(ctor, args){
    return new ctor(args);
};

var obj = creator(Constructor, ['someVar']);
var obj2 = creator2(Constructor, ['someVar']);

Both creator and creator2 work, so why would one choose creator over creator2?

1
  • apply is just a convenient way to set the value of this when calling function so you can just pass arguments (for example) rather than having to build up a call expression containing each argument. I don't think there is anything to recommend it other than convenience. If there are zero or one parameters, then it doesn't have any benefit over call. Commented Jan 18, 2016 at 23:00

1 Answer 1

2

Calling creator2 passes the args array as a single array parameter to the constructor.

Calling creator passes each item in the array as a separate parameter (via apply).

Sign up to request clarification or add additional context in comments.

5 Comments

Not sure that explains why one should be chosen over the other.
Thanks, this was some (important) detail that I overlooked. This also explains why return new (ctor.bind(null, args)); would not suit.
@RobG: They do two different things. You should chose whichever one you need.
The OP started with "I understand how Function.prototype.bind.apply works…" so I naively assumed that s/he knew how it works.
Maybe I should rephrase it as "I think I understand how ... works".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.