I have a list of arguments such as var args = ['blah', 1, 3.9] and I want to apply it to something that needs to be newed like new bleh.Thinggy(a, b, c).
I want to do the following var m = {}; bleh.Thinggy.apply(m, args);
I am worried there is something I am not thinking of does anyone know if this is safe?
Your current method is flawed, because prototype inheritance will not work as expected.
The equivalent of
method.apply(context, args)for constructors is:The roles of
Function.prototype.bindandFunction.prototype.applyare explained at the corresponding documentation. Remember:.bindreturns a function!To keep it simple, I’ll explain how to use
.bindfor a fixed number of arguments, say two. Then, the following have the same effect:And
If you’ve even glanced at the documentation, you’ll certainly understand the first form. The second form is trickier though. It works in this case, because the position of an argument in
Math.maxis not relevant. The maximum value of all arguments is considered, where all arguments are treated identically.Now, here follows an example with a custom function:
Because the position of arguments is significant in this case, the last example showed something weird. Indeed, the first argument is bound to “Oops” by the
.bindmethod. The arguments passed to the bound functionechoYouare appended to the arguments list. Additionally, you notice that the contextthiswas changed tonull.Interesting.. Let’s try to change the context using
.apply:As you can see,
this.foodstill points to method from the context as defined through.bind!So, we know how to lock the context of a function, as well as passing an arbitrary number of fixed arguments to a function. This can be applied to constructors, resulting in the function which I presented on top of the answer. To verify that it works as expected:
Note: I omitted parentheses
()in the one-liner, because constructors can be initialized without these.new Imageandnew Image()are behaving identically.To immediately read a property (or invoke a method) from the constructed method, you can either wrap the whole expression in parentheses or append
()to remove ambiguity:Note 2: It still holds that additional arguments are appended to the argument list. This property can also be used to “preset” the first arguments of a given constructor: