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(){

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()
var 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.

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 thoughts on “How to call anonymous function in Javascript?

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.