Home > Article > Web Front-end > JavaScript uses three methods to define implementation code analysis of functions
This article mainly introduces relevant information on 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
JavaScript Three implementation methods for defining functions
【1】Normal method
function print(msg){ document.write(msg); }
Several ways to call functions:
Function name (parameter 1 passed to the function, parameter 2 passed to the function, ....)
Variable = function name (parameter 1 passed to the function, passed Parameter 2 for the function,...)
For function calls with return values, you can also use the returned results 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
The above is the detailed content of JavaScript uses three methods to define implementation code analysis of functions. For more information, please follow other related articles on the PHP Chinese website!