call()
JavaScriptと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);
}
}