Necesito combinar el poder de los métodos de call()
y apply()
de JavaScript. El problema que estoy teniendo es que call()
conserva la referencia adecuada a this
, pero envía el argumento array que tengo como una matriz cuando lo necesito enviado como argumentos de función. El método apply()
envía los argumentos a la función muy bien cuando se utiliza una matriz, pero no sé cómo enviar la referencia adecuada al this
que el método call()
parece tener acceso naturalmente.Javascript pasa una matriz de argumentos utilizando `apply()`, pero mantenga `this` referencia de` call() `
A continuación se muestra una versión simplificada del código que tengo, es probable que se parece bastante inútil, pero es una buena manera de conseguir el punto a través de:
// 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);
}
}
El primer argumento de apply establece 'this' en lo que sea que pase ... si quiere' this == main', simplemente pase 'main' como primer argumento. – Snuffleupagus
@Snuffleupagus - Desafortunadamente, 'hub' no tiene conocimiento directo de 'main' –