Home >Web Front-end >JS Tutorial >Three ways to define functions in js
1. Use the function class to define a named function:
function function name ([parameter 1,. [parameter 2, [parameter N]]]) {
# firmciton: Must be option, define the keywords used in the function.
Function name: required, legal JavaScript identifier
Optional parameters: legal JavaScript identifier, external data can pass Parameters are transferred to the inside of the function
Statement group: optional, JavaScript program statement, when empty, the function has no action
return: Yes Option, when encountering this instruction, the function execution ends and returns. When this item is omitted, the function will end at the right curly brace
Expression: optional, its value is used as the return value of the function
2. Define functions by defining variables
All functions in JavaScript belong to Function objects, so you can use the function object constructor function to create a function
The essence is to create a function object
var variable name=new Function([parameter 1,[parameter 2, [Parameter N]]],[Function body]);
Function variable name: required, represents the function name (legal JavaScript identifier)
Parameters: Optional, the string used as a function parameter must be a legal JavaScript identifier. When the function has no parameters, it can be ignored
Function body: Optional, a string. Equivalent to a sequence of program statements in the function body, each statement is separated by a semicolon. For example:
##var f=new Function('name',"document.writeln('Function定义的函数<br>');"+"document.writeln('你好'+name);");f('zhangsan')
3、通过Function类创建匿名的函数
function(){函数体;}
因为是匿名函数故一般不传参,主要作为灰调函数和直接执行函数 如:
var a='a';
(function(){
var a='b';
alert(a)
})();
alert(a);
In the above code, two alert boxes will be output sequentially. The content of the first alert box is b, and the second one is a. Have you seen any benefits? Yes, using functions to execute directly can limit the scope of variables, so that the same variables in different scripts can coexist.
The above is the detailed content of Three ways to define functions in js. For more information, please follow other related articles on the PHP Chinese website!