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?
-
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.RobG– RobG2016年01月18日 23:00:49 +00:00Commented Jan 18, 2016 at 23:00
1 Answer 1
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).
answered Jan 18, 2016 at 22:54
SLaks
891k182 gold badges1.9k silver badges2k bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
RobG
Not sure that explains why one should be chosen over the other.
bvgheluwe
Thanks, this was some (important) detail that I overlooked. This also explains why
return new (ctor.bind(null, args)); would not suit.SLaks
@RobG: They do two different things. You should chose whichever one you need.
RobG
The OP started with "I understand how Function.prototype.bind.apply works..." so I naively assumed that s/he knew how it works.
bvgheluwe
Maybe I should rephrase it as "I think I understand how ... works".
lang-js