Home  >  Article  >  Web Front-end  >  Three implementation methods for defining functions in JavaScript

Three implementation methods for defining functions in JavaScript

韦小宝
韦小宝Original
2018-01-15 11:37:001490browse

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 js functions. Friends who are interested in JavaScript can refer to the following This article

Three implementation methods of defining functions in JavaScript

[1]Normal method

function print(msg){
  document.write(msg);
}

How to call functions One way:

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 return can also be used directly in the program The result, for example: alert("sum=" + square(2,3));

A function that does not specify any function value returns undefined.

【2】ConstructorMethod 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 the function body.

If only one string is passed, it is the function body.

【3】Function literal defines 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 function

The above is all the content of this article. I hope it can help everyone learn JavaScript! !

Related recommendations:

javascript determines whether the user has operated the page

##javascript implements the progress bar function example based on the timer

JavaScript implementation example of mouse wheel control page image switching function

The above is the detailed content of Three implementation methods for defining functions in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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