Defining Functions The definition of a function (also called a function declaration) consists of a series of function keywords
- The name of the function
- A list of function arguments enclosed in parentheses () and enclosed by commas
,
division - Function functions, enclosed in curly braces {}, are some JavaScript statements used to define function functions
for example
function square(number) { return number * number; }
The function square uses a parameter called number
This function has only one statement, which indicates that the function will self multiply the function parameter (i.e. number) and return
The return statement of the function determines the return value of the function
If you pass an object as a parameter and the function changes the properties of the object, such changes are visible outside the function
function myFunc(theObject) { theObject.make = "Toyota"; } var mycar = {make: "Honda", model: "Accord", year: 1998}, var x, y; X=mycar.make;//The value obtained by x is "Honda" myFunc(mycar); Y=mycar.make;//The value obtained by y is "Toyota" //(The value of the make attribute is changed in the function)
Function expression
var square = function(number) { return number * number }; var x = square(4); // X yields a value of 16
The function expression can also provide a function name, which is used inside the function to refer to itself
var factorial = function fac(n) {return n<2 ? 1 : n*fac(n-1)}; console.log(factorial(3));
The function expression is very convenient when passing the function as an argument to other functions
The following example demonstrates how to define a function called map, and then call an anonymous function as its first parameter
function map(f, a) { Var result=[],//Create a new array i; for (i = 0; i != a.length; i++) result[i] = f(a[i]); return result; } map(function(x) {return x * x * x}, [0, 1, 2, 5, 10]); //return [0, 1, 8, 125, 1000]
Define a function according to conditions, such as the following example
var myFunc; if (num == 0){ myFunc = function(theObject) { theObject.make = "Toyota" } }
When an object's property is a function, it is called a method
Call function
The calling function will actually execute these actions with the given parameters
For example, if you define the function square, you can call it as follows
square(5);
Functions must be in the domain where they are called, but functions can be declared after their calling statements, such as
console.log(square(5)); /* ... */ function square(n) { return n*n }
The function field refers to the place where the function is declared, or the whole program when the function is declared at the top level
The meaning can only use the above grammatical form function funcName(){}
The following example is invalid
console.log(square(5)); // square is not defined square = function (n) { return n * n; }
Functions can be recursive; That is, the function can call itself. The following example is to calculate the recursive factorial value
function factorial(n){ if ((n == 0) || (n == 1)) return 1; else return (n * factorial(n - 1)); } var a, b, c, d, e; a = factorial(1); // 1 Assign value to a b = factorial(2); // 2 Assign a value to b c = factorial(3); // 6 Assign a value to c d = factorial(4); // 24 Assign value to d e = factorial(5); // 120 assigned to e
Scope of function
A function can obtain any variable and sub function defined in its domain
- Functions defined in the global domain can obtain all variables defined in the global domain
- A child function defined in a function can obtain any variable defined in its parent function or obtained by its parent function
//The following variables are defined in the global scope domain var num1 = 20, num2 = 3, name = "Chamahk"; //This function is defined in the global scope function multiply() { return num1 * num2; } multiply(); // Returns 60 //Examples of nested functions function getScore () { var num1 = 2, num2 = 3; function add() { return name + " scored " + (num1 + num2); } return add(); } getScore(); // Returns "Chamahk scored 5"
Scope and function stack
recursion
Functions can point to and call themselves (call itself) in three ways:
- By using the function's name
- Use arguments. callee (ECMAScript (ES5) forces use of arguments. callee() in strict mode)
- Use a variable name under the scope to point to the function (an in scope variable references to the function)
Function definition:
var foo = function bar() { // statements go here };
In this function body, the following statements are equivalent
- bar()
- arguments.callee()
- foo()
Calling its own function is called recursive function
In a sense, recursion is close to a loop
Both execute the same code repeatedly, and both need a termination condition to avoid infinite loops or infinite recursion
var x = 0; while (x < 10) { // "x < 10" is the loop condition // do stuff x++; }
Convert to a recursive function and call it
function loop(x) { if (x >= 10) // "x >= 10" is the exit condition (equivalent to "!(x < 10)") return; // do stuff loop(x + 1); // the recursive call } loop(0);
Some algorithms cannot be implemented simply by loops. For example, when obtaining all nodes in the tree structure, it is much easier to implement recursively
function walkTree(node) { if (node == null) // return; // do something with node for (var i = 0; i < node.childNodes.length; i++) { walkTree(node.childNodes[i]); } }
Compared with the loop function, each recursive call here generates more recursion
In fact, recursive functions use the stack: the function stack
function foo(i) { if (i < 0) return; console.log('begin:' + i); foo(i - 1); console.log('end:' + i); } foo(3); // Output: // begin:3 // begin:2 // begin:1 // begin:0 // end:0 // end:1 // end:2 // end:3
Nested functions and closures
Nest another function inside a function
Nested functions are private members of container functions. It also forms a closure
A closure is an expression (usually a function) that can have its own environment and variables
A nested function is a closure, which means that a nested function can inherit the parameters and variables of the container function. In other words, the inner function contains the scope of the outer function.
- Internal functions can only be accessed in external functions
- The internal function forms a closure: it can access the parameters and variables of the external function, but the external function cannot use its parameters and variables
Nested functions:
function addSquares(a, b) { function square(x) { return x * x; } return square(a) + square(b); } a = addSquares(2,3); // returns 13 b = addSquares(3,4); // returns 25 c = addSquares(4,5); // returns 41
Internal functions form closures. You can call external functions and specify the parameters of external and internal functions
function outside(x) { function inside(y) { return x + y; } return inside; } // Think of it like: give me a function that adds 3 to whatever you give it fn_inside = outside(3); result = fn_inside(5); // returns 8 result1 = outside(3)(5); // returns 8
Save Variable
A closure must save all parameters and variables in its visible scope
The parameters passed in may be different for each call. The closure is actually recreated for each call to an external function
Memory will be released only when the return value of the inside is no longer referenced
Multilayer Nested Functions
Functions can be nested multiple levels
For example, function A can contain function B, and function B can contain function C. Both B and C form closures, so B can access A, C can access B and A
Closures can contain multiple scopes, which recursively contain all the function scopes containing them. This is called scope chaining
function A(x) { function B(y) { function C(z) { console.log(x + y + z); } C(3); } B(2); } A(1); // return 6 (1 + 2 + 3)
C can access y of B and x of A
- B forms a closure containing A, B can access A's parameters and variables
- C forms a closure containing B
- B contains A, so C also contains A, C can access the parameters and variables of B and A. In other words, C links the scopes of B and A in this order
The opposite is not true. A cannot access C because A cannot see the parameters and variables in B, C is a variable in B, so C is private to B.
name conflict
When two parameters or variables under the same closure scope have the same name, naming conflicts will occur
The closer scope has higher priority, and the farthest scope has the lowest priority. This is the scope chain
The first element of the chain is the innermost scope, and the last element is the outermost scope
function outside() { var x = 10; function inside(x) { return x; } return inside; } result = outside()(20); // returns 20 instead of 10
The naming conflict occurred on return x, The inside parameter x conflicts with the external variable x
The scope is {inside, outside, Global Object}
The inside has the highest priority and returns the passed 20 instead of the variable value 10 of the external function
Reading materials: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide
Review method: practice (write code once, run once, test once), Google where you don't understand, read and take notes
Bottom line principle: prefer rewriting once rather than copying and pasting
This review includes: part of function···
Review time: about 3 hours... I don't know why it takes so long···
]]>