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

Three ways to define functions in JavaScript

小云云
Release: 2018-02-03 11:22:20
Original
1640 people have browsed it

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);
}
Copy after login

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);
Copy after login

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);
Copy after login

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!

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