Home > Web Front-end > JS Tutorial > A brief discussion on the various definition methods and differences of js functions

A brief discussion on the various definition methods and differences of js functions

高洛峰
Release: 2016-12-03 15:53:27
Original
1013 people have browsed it

There are generally three ways to define a function:

1. Function keyword (function) statement:

function fnMethodName(x){
alert(x);
}
Copy after login

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>
Copy after login

【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>
Copy after login

【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>
Copy after login

The above article briefly discusses the various definition methods and differences of js functions is all the content shared by the editor


Related labels:
js
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template