我需要结合 JavaScriptcall()
和apply()
方法的强大功能。我遇到的问题是call()
保留了对 的正确引用this
,但是当我需要它作为函数参数发送时,将我拥有的参数数组作为数组发送。使用数组时,该apply()
方法将参数发送给函数就好了,但我不知道如何向它发送对该方法似乎自然可以访问的正确this
引用call()
。
下面是我拥有的代码的简化版本,它可能看起来毫无用处,但它是一个很好的理解要点的方法:
// 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);
}
}