1

Let's say I have a function and one of the parameters is for the name of the target variable.. Would it be possible for me to send a variable to the function like this:

function otherfunction(input){
...
}

function test {target) {
var x = 1;
target(x);
}

test(otherfunction);

The problem I have is that I'm making a greasemonkey script and one of the variable I need can't be returned from the function due to a limitation.. So this would be the alternative. I just don't know how to get it to work.. Any help would be much appreciated!!

2
  • 1
    Can you be more precise on what your technical limitation actually is? The normal solution to your problem, as Jacob has outlined would be to call otherfunction within the body of test, but this inevitably results in calling otherfunction() anyway. So you may as well just write otherfunction(1) instead of test(otherfunction). Commented Dec 26, 2010 at 3:42
  • @J. M Please accept correct answers to your questions by clicking inside the hollow checkmark. Thanks! :) Commented Dec 27, 2010 at 5:29

1 Answer 1

4

Your example (almost) works:

function otherfunction(input){
   alert(input);
}

function test(target) {
   if(typeof target !== 'function') {
      alert('target is not a function!');
      return;
   }
   target(1); //invokes the passed-in function, passing in 1
}

test(otherfunction); //alerts 1

//You can also do it with an anonymous function too:

test(function(arg) {
  alert(arg * 5);
}); //alerts 5

jsFiddle example

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

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.