1

My series of methods are like so :

onUpdateAcrossDown ( findAcrossAndDownWords( across_index, down_index ) )

I want to reuse findAcrossAndDownWords, so I'd like it to return my two objects that I can pass into other methods if need be.

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.
}

The trouble is, the return I am using does not properly pass across_word, down_word .

onUpdateAcrossDown: function(across_word, down_word) {
 // How do I get across_word and down_word here properly?

2 Answers 2

4

If you want to use the values in an array as parameters to a function, you have to call the function with .apply()

var results = findAcrossAndDownWords( across_index, down_index );
onUpdateAcrossDown.apply(whatever, results);

The .apply() method takes two arguments: the value to use for this in the called function, and an array containing the parameters to pass.

Sign up to request clarification or add additional context in comments.

7 Comments

strikes again! Thanks so much!
Is that whatever relevant? It's returning undefined ;)
@Trip well I couldn't tell from your code whether the this value inside the function is important. If it is, then that's what you pass; otherwise it doesn't really matter. (By "whatever" I just meant, "something appropriate", in other words.)
@Trip: I do hope you know what this references when you're passing it to .apply, because this can point to the global object, so you might be creating unwanted globals or trying to access undefined properties
@EliasVanOotegem well if he's passing undefined then it's probably OK, so long as it's working.
|
1

You could, instead of nesting calls, pass the second function as an argument:

findAcrossAndDownWords(across_index, down_index, onUpdateAcrossDown);

function findAcrossAndDownWords(object1, object2, callNext)
{
    //do stuff
    return callNext(object1, object2);
}

Or, change the function definition of the second function to:

function UpdateAcrossDown(anArray)
{
    var obj1 = anArray[0], obj2 = anArray[1];
}

Or, if you're allways going to call the same function:

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.