2

How to call back a function which is defined in a variable(I did this)... More than this how to pass variable into that function(which is also defined as variable)

Example: Functionvariable,variable are variables....

function ffunction(Functionvariable,variable){
     Functionvariable(variable); //This is actually not working...how to do this...
}

I tried this,

function ffunction(Functionvariable,variable){
     eval(Functionvariable + '('+ variable + ')'); //no luck
}

This is worked...

function ffunction(Functionvariable,variable){
         eval(Functionvariable)(variable);
    }
9
  • how is this method called Commented Mar 25, 2014 at 7:35
  • I hope that your arg is not called Function because Function has a special meaning in javascript Commented Mar 25, 2014 at 7:36
  • Your first example is correct, if you're trying to do what it looks like. ffunction(alert, 3) will alert 3. Commented Mar 25, 2014 at 7:37
  • do you have any errors in console? Commented Mar 25, 2014 at 7:39
  • take this for example: var g = function(){alert("called")};function f2(fn,v){fn(v)};f2(g,1) This is the same example as yours but it works Commented Mar 25, 2014 at 7:40

2 Answers 2

2

Just avoid reserved words and you shall be fine with your first solution.
Here is the fiddle http://jsfiddle.net/6R3ye/

function dummy(func, v){
    eval(func)(v);
};
var f = 'alert';
var x = 'abc';
dummy(f, x);
Sign up to request clarification or add additional context in comments.

3 Comments

I mentioned.. func here is also variables... I am passing some name as variable....
Now it's what you want
@AnishCharles it was a bit hard to understand what you mean, because variable can also hold function instance. Please accept the answer and possibly upvote. Good luck.
0

I gathered 4 methods you can use, with 1 or more params

And a fiddle

function ffunction(fn, p1, p2) {
  console.log("ffunction is calling \n" + fn.toString() + "\nwith " + p1.toString());

  eval(fn)(p1, p2);
  fn(p1, p2);
  fn.call(fn, p1, p2);
  fn.apply(fn, [p1, p2]);
}

function f1(p1, p2){
  console.log("f1 got " + p1.toString() + " and " + p2.toString());
}

ffunction(f1, 'foo', 'bar');

1 Comment

You haven't read the comments. Only your first solution will work if fn holds the name of the function as a string. The problem is already solved. @Anish please accept the working answer.

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.