The examples in this article describe several ways to define JS functions. Share it with everyone for your reference, the details are as follows:
The definition of JS functions is relatively flexible. It is different from other languages. Each function is maintained and run as an object.
Let’s take a look at some commonly used definitions:
function func1([parameter]){/*function body*/}
var func2=function([parameter]){/*function body*/};
var func3=function func4([parameter]){/*function body*/};
var func5=new Function();
The first method above is the most commonly used method, needless to say.
The second is to assign an anonymous function to a variable, calling method: func2([function]);
The third method is to assign func4 to the variable func3 and call the method: func3([function]); or func4([function]);
The fourth way is to declare func5 as an object.
Look at their differences:
function func(){ //函数体 } //等价于 var func=function(){ //函数体 }
But they are also defining functions, and there are certain differences in usage.
<script> //这样是正确的 func(1); function func(a) { alert(a); } </script>
<script> //这样是错误的,会提示func未定义,主要是在调用func之前没有定义 func(1); var func = function(a) { alert(a); } //这样是正确的,在调用func之前有定义 var func = function(a) { alert(a); } func(1); </script>
The third definition can be understood in the same way.
The fourth definition method also requires declaring the object before it can be referenced.
I hope this article will be helpful to everyone in JavaScript programming.