Javascript pass array of arguments using `apply()`, but keep `this` reference from `call()`
apply, call, javascript
Solution
What? Apply passes the scope as well...
method.apply(this, [args]);
Edit:
In your code you have the main object defined in the containing scope so you can simply do;
this.methods[i].call(main);
or
this.methods[i].apply(main, [args]);
Problem
I need to combine the power of JavaScript's `call()` and `apply()` methods. The problem I am having is that `call()` retains the proper reference to `this`, but sends the argument array that I have as an array when I need it sent as function arguments. The `apply()` method sends the arguments to the function just fine when using an array, but I don't know how to send it the proper reference to `this` that the `call()` method seems to naturally have access to. Below is a simplified version of the code that I have, it probably looks pretty useless, but its a good way to get the point across: ``` // AN OBJECT THAT HOLDS SOME FUNCTIONS var main = {}; main.the_number = 15; main.some_function = function(arg1, arg2, arg3){ // WOULD VERY MUCH LIKE THIS TO PRINT '15' TO THE SCREEN alert(this.the_number); // DO SOME STUFF WITH THE ARGUMENTS ... }; // THIS STORES FUNCTIONS FOR LATER. // 'hub' has no direct knowledge of 'main' var hub = {}; hub.methods = []; hub.methods.push(main.some_function); hub.do_methods = function(arguments_array){ for(var i=0; i<this.methods.length; i++){ // With this one, '15' is printed just fine, but an array holding 'i' is // just passed instead if 'i' itself this.methods[i].call(arguments_array); // With this one, 'i' is passed as a function argument, but now the // 'this' reference to main is lost when calling the function this.methods[i].apply(--need a reference to 'main' here--, arguments_array); } } ```