2

I need to store an anonymous function passed as argument of my "named" function in Javascript, and then call it later.

How can I do this? I already know how to pass an anonymous function as an argument, but I don't know how to deal with it when I'm "on the other side" of the code.

Thank you

1
  • just store it in any relative to the fuction/context. like function xxx(f){ this.handler=f; } //change this to some other object, self, whatever. later you can just call it w/ this.handler() Commented Mar 24, 2011 at 11:51

4 Answers 4

5

Functions in JavaScript are first-class members which means that you can work with them just as you would any other data type in the language - you can pass them as arguments, keep them as member variables inside of other functions, return them from functions etc.

In the case you've asked about, it works just like any other named variable with the neat addition that you can invoke the function as below since it is a function:

function myFunc(anonymous){
    var arg1;
    anonymous(arg1);
}

myFunc(function(arg1){console.log(arg1)});
Sign up to request clarification or add additional context in comments.

Comments

1

Just call it using the name of the parameter.

function callThisLater(laterFunction) {
  // ...
  laterFunction(args);
}

callThisLater(function (arg1) {
    alert("We've been called!");
});

Comments

1

Here is basic example:

function Foo(func) {
    this.Func = func;
    this.Activate = function() {
        this.Func();
    };
}

var foo = new Foo(function() { alert("activated"); });
foo.Activate();

I believe that what you missed is using the () to "activate" the function - as far as I understand you reached the point of "storing" the function to variable.

Comments

0

can you assign your anonymous function passed as an argument to a named function to a global variable inside the named function and then can used the global variable as a reference to anonymous function.

1 Comment

So you're not talking about global variables then, since it's a variable inside a function. That should probably be edited so it's not confusing.

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.