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);
}
}
The Difference Between call() and apply() The difference is: The call() method takes arguments separately. The apply() method takes arguments as an array. The apply() method is very handy if you want to use an array instead of an argument list.
JavaScript is always pass-by-value. This means everything in JavaScript is a value type and function arguments are always passed by value.
In Javascript objects and arrays follows pass by reference. so if we are passing object or array as an argument to the method, then there is a possibility that value of the object can change.
In JavaScript array and Object follows pass by reference property. In Pass by reference, parameters passed as an arguments does not create its own copy, it refers to the original value so changes made inside function affect the original value.
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With