我需要结合 JavaScript 的
下面是我拥有的代码的简化版本,它可能看起来没什么用,但这是一个很好说明问题的方法:
call()
和 apply()
方法的力量。我遇到的问题是,call()
保留了对 this
的正确引用,但将参数数组作为数组发送,而我需要将它作为函数参数发送。使用数组时,apply()
方法可以很好地将参数发送到函数中,但我不知道如何向其发送 call()
方法似乎自然具有的对 this
的正确引用。下面是我拥有的代码的简化版本,它可能看起来没什么用,但这是一个很好说明问题的方法:
// 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);
}
}
this
设置为你传递的任何内容... 如果你想让this == main
,那么只需将main
作为第一个参数传递即可。 - Snuffleupagus