SoFunction
Updated on 2025-03-01

Three implementation methods for defining JavaScript functions

Three implementation methods for defining JavaScript functions

【1】Normal method

function print(msg){
  (msg);
}

Several ways to call functions:

Function name (parameter 1 passed to function, parameter 2 passed to function,….)

Variable = function name (parameter 1 passed to function, parameter 2 passed to function,….)

For function calls with return values, you can also use the returned result 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();

   //Constructor method defines javascript functions. Pay attention to the F capitalization in Function.    var add=new Function('a','b','return a+b;');


    //Calling the add function defined above    var sum=add(3,4);
    alert(sum);

Note: Accept any multiple string parameters, and the last parameter is the function body.

If you pass only one string, it is the function body.

【3】Functions define functions directly

 //Define functions using the function directly   var result=function(a,b){return a+b;}
 
   //Calling a function defined using a function directly   var sum=result(7,8);
   alert(sum); 

Note: The direct quantity of a function is an expression that can define anonymous functions

If you have any questions, please leave a message or go to the community of this website to exchange and discuss. Thank you for reading. I hope this article can help you. Thank you for your support for this website!