Home >Web Front-end >JS Tutorial >A brief discussion on the various definition methods and differences of js functions
There are generally three ways to define a function:
1. Function keyword (function) statement:
function fnMethodName(x){ alert(x); }
2. Function literals (Function Literals):
var fnMethodName = function(x){ alert(x);}
3.Function() constructor:
var fnMethodName = new Function('x', 'alert(x);')
The above three methods define the same method function fnMethodName, The first is the most commonly used method. The latter two copy a function to the variable fnMethodName, and this function has no name, that is, an anonymous function. In fact, quite a few languages have anonymous functions.
Examples are as follows:
【The first type - function keyword (function) statement】
<script type="text/javascript"> function add(num1,num2) { return num1+num2+200; } var sum=add(122,10000); window.document.write(sum); </script>
【The second type - function literals (Function Literals):】
<script type="text/javascript"> var add=function(num1,num2) { return num1+num2+200;} var sum=add(122,300); window.document.write(sum); </script>
【Chapter Three types of -Function() constructors:】
<script type="text/javascript"> var add=new Function("num"," return num+200");//此时Function 这种方法用的比较少 var sum=add(122); window.document.write(sum); </script>
The above article briefly discusses the various definition methods and differences of js functions is all the content shared by the editor