我的一系列方法是这样的:
onUpdateAcrossDown ( findAcrossAndDownWords( across_index, down_index ) )
我想重用findAcrossAndDownWords
,所以我希望它能够返回我可以传递给其他方法的两个对象。
findAcrossAndDownWords: function(across_index, down_index) {
across_word = across_index[0] // <-- not real, just representing that it becomes an object here.
down_word = down_index[0]
return [across_word, down_word] // <-- This is where my problem is. Not sure how to return a double param for my parent function.
}
问题是,我使用的return
没有正确传递across_word, down_word
。
onUpdateAcrossDown: function(across_word, down_word) {
// How do I get across_word and down_word here properly?
答案 0 :(得分:4)
如果要将数组中的值用作函数的参数,则必须使用.apply()
var results = findAcrossAndDownWords( across_index, down_index );
onUpdateAcrossDown.apply(whatever, results);
.apply()
方法有两个参数:被调用函数中用于this
的值,以及一个包含要传递的参数的数组。
答案 1 :(得分:1)
您可以将第二个函数作为参数传递,而不是嵌套调用:
findAcrossAndDownWords(across_index, down_index, onUpdateAcrossDown);
function findAcrossAndDownWords(object1, object2, callNext)
{
//do stuff
return callNext(object1, object2);
}
或者,将第二个函数的函数定义更改为:
function UpdateAcrossDown(anArray)
{
var obj1 = anArray[0], obj2 = anArray[1];
}
或,如果你总是打算调用相同的功能:
function findAcrossAndDownWords(object1, object2, callNext)
{
//do stuff
return UpdateAcrossDown(object1, object2);//loses call context
return UpdateAcrossDown.apply(this,arguments);//preserve called context
//or even
return UpdateAcrossDown.apply(this,[object1,object2]);//preserve called context
}