0

I have the following code with a function:

var f1;

var getFunction = function (f2) {
    f1 = f2;   
}

Later in the code, I need to call f1 (that was actually received as a parameter). Note that I don't know the function's name when I call it.

How do I make this call?

12
  • 8
    so you call it... f1(); Commented Jul 7, 2016 at 12:03
  • 1
    Later in the code where? Why don't you know the name? By your example, you know it's either f1 or f2. Did you try something and experience failure? Is there something async involved? The question is very unclear. Commented Jul 7, 2016 at 12:08
  • 1
    When you assign a function to f1, guess what... its name is f1. Commented Jul 7, 2016 at 12:09
  • 1
    @Kaiido: Do you honestly not understand the point he was making? Commented Jul 7, 2016 at 12:14
  • 1
    @Kaiido ...a name by which you can call the function is... – I was trying to keep it simple and straight forward. There isn't a lot of space in comments to list all caveats and asterisks and it doesn't make it easier to understand either. Commented Jul 7, 2016 at 12:19

3 Answers 3

2
function test(){
     alert(1);
}
var f1;

var getFunction = function (f2) {
    f1 = f2; 
    f1();  
}

getFunction(test);

Here is the DEMO

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

Comments

1

This is no different than callbacks in Ajax call or anywhere else where you pass around a reference to a function. You just execute it via the variable that you store the function in.

var f1;

var setFunction = function (f2) {
    f1 = f2;   
}

setFunction( function(x) { console.log(x); } );

f1("test");

If you need to execute it with scope, than you need to use .apply() or .call()

Comments

0
var f1;

var getFunction = function (f2) {
    f1 = f2;   
}
var b = function(){}
getFunction(b);
f1();

1 Comment

Could you provide some context to your answer, explaining how it works and addresses the question?

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.