How to call anonymous function in Javascript?<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

How to call anonymous function in Javascript?

Posted on: May 19, 2012

You may have anonymous function that you want to call later in the same method (or to pass this one by parameter and call this one later). To be able to have a reference to this anonymous function, you need to use a variable that will keep a reference to this anonymous function. Later, when you want to use it, you simply need to call it by writing the variable name with parentheses.

1var anonymous= function(){
2 alert("Test123");

From here you can have more complex prototype (Javascript class mechanism).

1function MyClass(val1, val2){
2 this.val1 = val1;
3 this.val2 = val2;
4 this.function1 = function() { alert(this.val1); }
7var x = new MyClass('Test','Hello');

This example show you that you can have an anonymous function that can be called later like the previous example.