Home > Web Front-end > JS Tutorial > body text

Analysis of several definition methods of JS functions_javascript skills

WBOY
Release: 2016-05-16 15:25:24
Original
1743 people have browsed it

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(){
  //函数体
}

Copy after login

But they are also defining functions, and there are certain differences in usage.

<script>
//这样是正确的
func(1);
function func(a)
{
  alert(a);
}
</script>
Copy after login
<script>
//这样是错误的,会提示func未定义,主要是在调用func之前没有定义
func(1);
var func = function(a)
{
  alert(a);
}
//这样是正确的,在调用func之前有定义
var func = function(a)
{
  alert(a);
}
func(1);
</script>

Copy after login

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.

Related labels:
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