Javascript function
First, javascript functions
Concept of function
A function is a block of frequently used code wrapped around the keyword function that is called when function is called
Js functions are declared as follows:
1. Direct statement
function func1(a, b) { console.log(a + b); } func1 (2, 3); / / 5Copy the code
2. Function expressions (anonymous functions)
var func1 = function (a, b) { console.log(a + b ); }; func2(2, 3); / / 5Copy the code
constructor
var func1 = new Function('a', 'b', 'console.log(a+b)'); Func3 - a non-class function (2, 3); / / 5Copy the code
Es6 arrow function ()=>{}
Js function call
1. Call the function directly:
Function fn(){console.log(1); } // function call fn();Copy the code
2. Method call Here refers to assigning a value to an object and then making a call using the object’s method
Var func = function() {alert(" am I a function? ); }; // Assign it to an object var o = {}; o.fn = func; // Call o.fin ();Copy the code
In the case of the constructor, this refers to the current object. In the case of the constructor, this refers to the current object
Expression of a function
A function expression is a function stored in a variable and an anonymous function is when the variable is empty
Var fn = function(){console.log(" function expressions: store functions in variables "); }; fn(); /Copy the code
A method that can be executed without calling an anonymous function (execute the function immediately)
(function(){console.log(" anonymous function execution "); }) ();Copy the code
Immediately executed functions are undeclared, released immediately after a single execution, suitable for initialization, executed once, destroyed after execution, does not take up space, there is a precompilation, there is also an execution-time context, the expression is executed after the function name is automatically ignored
Function parameters
Function arguments are usually taken from the parent element. Line arguments: formal arguments that declare an argument to the function. Arguments: actual arguments, the values assigned to the parameters when the function is called
Function func(argument 1, argument 2){// function execution code} func(argument 1, argument 2); // Pass the parameter when callingCopy the code
Function return value
The return value of a function is the result returned after the function is executed. Each function returns a result after execution. Return can only be used in functions, not elsewhere. If there is no return value, the default is underpay
Function func1(){console.log(" function func1 performs content "); } function func2(){console.log(" function func2 performs content "); return 1; var a = 2; console.log(a); } // Undefined console.log("func1 returns result: "+func1()); //undefined console.log("func2 returns a result "+func2()); / / 1Copy the code