Home » Web » Javascript » How to call anonymous function in Javascript?

How to call anonymous function in Javascript?

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.

var anonymous= function(){
    alert("Test123");
};
anonymous();

Pretty simple, isn’t?

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

function MyClass(val1, val2){
    this.val1 = val1;
    this.val2 = val2;
    this.function1 = function()
    {
        alert(this.val1);
    }
}
//...
var x = new MyClass('Test','Hello');
x.function1();

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

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

2 Responses so far.

  1. I like your blog. I don’t know if you’re from Montreal specifically, but I added your feed to http://www.montrealhackers.com/ .

    Cheers!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.