JavaScript anonymous functions with delegate usage examples

  • 2020-03-30 03:36:32
  • OfStack

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
  <!-- C# Anonymous functions --> 
  <title></title> 
  <script type="text/javascript"> 
    var f1 = function (x, y) { //[1] define an anonymous function and point to it with the variable f1 (f1 is equivalent to a delegate, so f1 can be used as a function).
      return x + y; 
    } 
 
    //Call this anonymous function
    alert(f1(5, 6)); //The output of 11
    //[2] you can also declare anonymous functions for immediate use
    alert(function (a, b) { return a + b } (10, 2)); //Directly declare an anonymous function (a, b) {return a + b}, and then directly use function (a, b) {return a + b} (10, 2). Not even f1, which refers to the anonymous function (a, b) {return a + b}. I'm going to print 12
 
    //[3] anonymous function without parameters
    var f2 = function () { alert(" hello ") }; 
    f2(); //I'm going to say "hello"
 
    var f3 = function () { return 5 }; 
    alert( f3() + 5);//The output of 10
  </script> 
</head> 
<body> 
 
</body> 
</html>

Related articles: