Difference between “anonymous function” and “function literal” in JavaScript?

后端 未结 5 1229
青春惊慌失措
青春惊慌失措 2020-12-09 12:55

The book Learning JavaScript defines anonymous functions as follows...

Functions are objects. As such, you can create them - just like a String

5条回答
  •  囚心锁ツ
    2020-12-09 13:26

    An anonymous function is simply a function with no name.

    function(a, b){
      return a + b;
    }
    

    The above code would be useless as it has no name to which you could call it with. So they are usually assigned to a variable.

    var func = function(a, b){
      return a + b;
    }
    

    This is helpful because you can pass an anonymous function to another function or method without having to create the function before hand, as demonstrated below.

    function bob(a){
      alert(a());
    }
    
    bob(function(){
      return 10*10;
    })
    

提交回复
热议问题