Home >Web Front-end >JS Tutorial >Three ways to define functions in JavaScript
This article mainly introduces relevant information to you about the three implementation methods of defining functions in JavaScript. I hope that through this article you can master the three methods of defining functions. Friends in need can refer to it. I hope it can help you.
Three implementation methods of JavaScript defined functions
【1】Normal method
function print(msg){ document.write(msg); }
Several ways to call a function:
Function name (parameter 1 passed to the function, parameter 2 passed to the function,...)
Variable = function name (parameter 1 passed to the function, parameter 2 passed to the function,...)
For function calls with return values, the returned results can also be used directly in the program, For example: alert("sum=" + square(2,3));
A function that does not specify any function value returns undefined.
【2】Constructor method new Function();
//构造函数方式定义javascript函数 注意Function中的F大写 var add=new Function('a','b','return a+b;'); //调用上面定义的add函数 var sum=add(3,4); alert(sum);
Note: accept any number of string parameters, the last parameter is function body.
If only one string is passed, it is the function body.
[3] Function literal definition function
//使用函数直接量的方式定义函数 var result=function(a,b){return a+b;} //调用使用函数直接量定义的函数 var sum=result(7,8); alert(sum);
Note: Function literal is an expression, which can define anonymous functions.
Related recommendations:
PHP custom function to determine which submission method
How to use built-in functions and custom functions in JS
A case of php custom function implementing array comparison function
The above is the detailed content of Three ways to define functions in JavaScript. For more information, please follow other related articles on the PHP Chinese website!