I am small and live in Wuhan, do two years of new media, ready to use 6 months time to switch to the front end of the industry.
Lesson Objective for today
Yesterday we studied the Date instance object method in detail based on search. Today is mainly based on search to learn the basic Function data structure, it is a good day for learning, come on, small and !!!!
what
In JavaScript, every Function is actually a Function object. See the Function page for its properties and methods.
The return value
If a function does not use a return statement, it returns undefined by default.
To return a specific value, the function must use a return statement to specify a value to return. (Except for calling a constructor using the new keyword).
Arguments & parameters
When a function is called, the values passed to the function are called arguments to the function (value passing), and the corresponding function arguments are called parameters.
If the argument is a variable that contains the original value (number, string, Boolean), the value of the argument does not change even if the function internally changes the value of the corresponding parameter.
If the argument is an object reference, the corresponding argument refers to the same object as the argument. If the function internally changes the value of the corresponding parameter, the value of the object to which the argument points changes when it returns:
how
There are several ways to define functions
Function declaration (function statement)
There is a special syntax for declaring functions (see function statements for details) :
function name([param[, param[, ... param]]]) { statements }
Copy the code
name
The function name.
param
The name of the argument passed to a function. A function can have up to 255 arguments.
statements
The declarations that make up the body of a function.
Function expression
Function expressions and function declarations are very similar, and they even share the same syntax (see function expressions for details).
A functional expression may be part of a larger expression. You can define function “names” (which can be used on the call stack, for example) or use “anonymous” functions. Function expressions are not promoted and therefore cannot be called before definition.
var myFunction = function name([param[, param[, ... param]]]) { statements }
Copy the code
name
The function name can be omitted. When the function name is omitted, the function becomes anonymous.
param
The name of the argument passed to a function. A function can have up to 255 arguments.
Statements Statements that form the body of a function. Here is an example of an anonymous function (the function has no name) :
var myFunction = function() {
// statements
}
Copy the code
You can also name the function when defining it:
var myFunction = function namedFunction(){
// statements
}
Copy the code
The advantage of named function expressions is that when we encounter errors, the stack trace shows the function name, making it easy to find errors.
As you can see, neither of the above examples begins with function. Function statements that do not begin with function are function expression definitions.
IIFE (Immediately Invokable Function Expressions) is usually used when a Function is used only once. IIFE (Immediately Invokable Function Expressions) is usually used when a Function is used only once.
(function() {
statements
}) ();Copy the code
IIFE is a function expression called immediately after a function declaration.
Function generator declaration (function*
Statement)
Function declarations have a special syntax (see function* statement for details) :
function* name([param[, param[, ...param]]]) { statements }
Copy the code
name
Function name.
param
The name of the argument passed to a function. A function can have up to 255 arguments.
statements
The declarations that make up the body of a function.
Function generator expression (function*
Expression)
Constructor expressions are similar to function declarations and have the same syntax (see function* statement for details) :
function* [name] ([param] [, param] [..., param]) { statements }
Copy the code
name
Function name. The function name can be omitted, in which case the function becomes anonymous.
param
The name of the argument passed to the function. A function can have up to 255 arguments
statements
The declarations that make up the body of a function.
Arrow function expression(= >)
Arrow function expressions have a shorter syntax and combine this value lexically (see Arrow functions for details):
([param] [, param]) => { statements } param => expression
Copy the code
param
Parameter name. Zero parameters should be represented by (). No parentheses are required when there is only one argument (e.g. Foo => 1).
statements or expression
Braces are required for multiple statements, but not for a single expression. Expression is also the implicit return value of this function.
Function constructor
Note: Using the Function constructor to create functions is not recommended, as it requires a Function body as a string that may prevent some JS engine optimizations and cause other problems.
For all other objects, Function objects can be created with the new operator:
new Function (arg1, arg2, ... argN, functionBody)
Copy the code
arg1, arg2, … argN
Functions use zero or more names as formal parameter names. Each must be a string or comma-separated list of strings that conform to valid JavaScript identifier rules, such as “x”, “theValue”, or “a,b”.
functionBody
A string that contains a JavaScript declaration statement defined by a constituent function.
Calling the constructor of Function as a Function (without the new operator) has the same effect as calling the constructor of Function.
Constructor of a generator function
Note: GeneratorFunction is not a global object, but can be retrieved from the constructor instance. See generator functions for details.
Note: Using constructor function constructor to create functions is not recommended, as it requires a function body as a string that may prevent some JS engine optimizations and cause other problems.
All other objects, GeneratorFunction objects can be created with the new operator:
new GeneratorFunction (arg1, arg2, ... argN, functionBody)
Copy the code
arg1, arg2, … argN
Functions use zero or more names as formal parameter names. Each must be a string or comma-separated list of strings that conform to valid JavaScript identifier rules, such as “x”, “theValue”, or “a,b”.
functionBody
A string that contains a JavaScript declaration statement defined by a constituent function.
Calling the constructor of GeneratorFunction as a function (without the new operator) has the same effect as calling the constructor of GeneratorFunction.
Object method definition
Starting with ECMAScript 6, you can define your own methods in a much shorter syntax, similar to getters and setters. See Method Definitions for details.
grammar
const obj = {
get property() {},
set property(value) {},
Property (parameters)... {},* the generator (the parameters...). {}, asyncProperty (parameters)... {}, async* the generator (the parameters...). {}, // with computed keys get [property]() {}, set [property](value) {}, [property] (the parameters...). {},* / generator (parameters)... {}, async[property] (the parameters...). {}, async* / generator (parameters)... {},}; Copy the code
case
This shorthand syntax is similar to the getter and setter syntax of ECMAScript 2015.
The following code:
var obj = {
foo: function() {
/* code */
},
bar: function() {
/* code */ } }; Copy the code
Can now be abbreviated as:
var obj = {
foo() {
/* code */
},
bar() {
/* code */ } }; Copy the code
Note: The shorthand syntax uses named functions rather than anonymous functions (e.g…. Foo: function () {}…). . Named functions can be called from the function body (which is impossible for anonymous functions because there are no identifiers to reference).
Comparison of declaration modes
Based on contrast
Compare the following example:
A Function defined by the Function constructor and assigned to the variable multiply:
var multiply = new Function('x'.'y'.'return x * y');
Copy the code
A function called multiply declares:
function multiply(x, y) {
return x * y;
} // No semicolons
Copy the code
Multiply is the function expression of an anonymous function assigned to the variable multiply:
var multiply = function(x, y) {
return x * y;
};
Copy the code
The function expression of a function named func_named is assigned to the variable multiply:
var multiply = function func_name(x, y) {
return x * y;
};
Copy the code
The difference
There are some subtle differences, but they all work the same way
- There are differences between function names and function variables.
- Function names cannot be changed, but function variables can be redistributed.
- Function names can only be used inside functions.
- Using a function name outside of a function causes an error (if the function was preceded by a
var
The statement declares thatundefined
).
Such as:
var y = function x() {};
alert(x); // throws an error
Copy the code
The Function name is also present when the Function is serialized through Function’s toString method.
On the other hand, a variable assigned by a function is limited only by its scope, which is guaranteed to contain the scope at which the function was declared.
As the fourth example shows, the function name is not the same as the variable assigned by the function. They have nothing to do with each other. The function declaration also creates a variable with the same name as the function.
Thus, unlike function expression definitions, functions defined as function declarations can be accessed by function names in the scope in which they are defined:
Use functions defined with new Function without Function names. However, in the SpiderMonkey JavaScript engine, the serialized form of its function behaves as if it had a name called “anonymous”.
For example, use alert(new Function()) to print:
function anonymous() {
}
Copy the code
In fact, the function has no name, and anonymous is not a variable that can be accessed within the function.
For example, the following example will cause an error:
var foo = new Function("alert(anonymous);");
foo();
Copy the code
Unlike functions defined through Function expressions or Function constructors, functions defined by Function declarations can be used before they are declared. Here’s an example:
foo(); // alerts FOO!
function foo() {
alert('FOO! ');
}
Copy the code
The function defined by a function expression inherits the current scope. In other words, functions form closures.
Object properties
The property name | describe | Method of use |
---|---|---|
arguments | Not recommended The attribute represents the argument to the function passed in. It is an array-like object. Deprecated for many years now, the recommended practice is to use what is available inside the functionarguments Object to access the arguments to the function. When a function is called recursively (the same function is run multiple times at the same time, with multiple sets of arguments), thenarguments Property is the argument passed in the last call to this function. If the function is not executing, the value ofarguments The value of the property isnull . |
functionName.arguments |
arity | Have been abandoned Return the number of parameters to a function, is an ancient property that no longer supports browsers, you should uselength Property instead of. |
functionName.arity |
caller | Not recommended If a functionfunctionName Is in theGlobal scope Is called within, thenfunctionName.caller fornull If, on the other hand, a function is called within the scope of another functionfunctionName.caller Refers to the one that called itThe function , the common form of the propertyarguments.callee.caller To replace the abandonedarguments.caller . |
functionName.caller |
callee | Not recommended Callee puts back a reference to the function itself being executed, which isarguments A property of. |
arguments.callee |
displayName | Not recommended Gets the display name of the function. |
functionName.displayName |
length | Length is an attribute value of the function object. Length is the number of parameters that must be passed to the function. The number of parameters does not include the number of remaining parameters, only the number of parameters before the first one has a default value. In contrast, arguments.length is the number of actual arguments passed when the function is called. | functionName.length |
name | Returns the name of a function declaration, usednew Function(...) Syntax-created functions or justFunction(...) The Create Function object and its name areanonymous . |
functionName.name |
prototype | Function objects have properties__proto__ The implicit stereotype of an object points to the stereotype of the constructor that constructed the object. |
functionName.prototype |
Matters needing attention
callee
- This property is valid only when the function is executed
- It has a length attribute that can be used to get the number of parameters, so it can be used to compare whether the number of parameters and arguments is the same, i.e. whether arguments.length is equal to arguments.callee.length
- It can be used to recurse anonymous functions.
var a = function() {
console.log("arguments.callee"); // arguments.callee
console.log(arguments.callee);
// Print the effect on the browser console
/ / ƒ () {
// console.log("arguments.callee"); // console.log(arguments.callee); // console.log("arguments.callee.length"); // console.log(arguments.callee.length); // } // Run the print effect as a node in a js file //[Function: a] console.log("arguments.callee.length------a"); //arguments.callee.length console.log(arguments.callee.length); / / 0 } var b = function(n,m) { a(); console.log("arguments.callee.length------b"); //arguments.callee.length console.log(arguments.callee.length); / / 2 } b(); Copy the code
length
- Note that this refers to the number of parameters. If the parameter is passed as defined, it will not be evaluated
console.log(Function.length); / * 1 * /
console.log((function() {}).length); /* 0 */
console.log((function(a) {}).length); / * 1 * /
console.log((function(a, b) {}).length); /* 2 etc. */
console.log((function(. args) {}).length); // 0, rest parameter is not counted console.log((function(a, b = 1, c) {}).length); // 1, only parameters before the first one with // a default value is counted console.log((function(a = 1, b, c) {}).length) / / 0 console.log((function(b, a = 1, c) {}).length) / / 1 console.log((function(b, c, a = 1) {}).length) / / 2 Copy the code
The Function scope
It should be noted that nested Function expressions and Function declarations are not parsed repeatedly in functions generated by parsing the Function constructor string. Such as:
var foo = (new Function("var bar = \'FOO! \ '; \nreturn(function() {\n\talert(bar); \n});"()));foo(); Function () {\n\talert(bar); This part of \n}" is not parsed repeatedly.
Copy the code
Function declarations are easily (and often accidentally) converted into function expressions. When it is no longer a function declaration:
- Becomes part of the expression
- No longer a “source element” of a function or script itself. A “source element” is a non-nested statement in the body of a script or function.
var x = 0; // source element
if (x === 0) { // source element
x = 10; / / the source element
function boo() {} / / the source element
}
function foo() { // source element var y = 20; // source element function bar() {} // source element while (y === 10) { // source element function blah() {} / / the source element y++; / / the source element } } Copy the code
This paragraph does not quite understand ~~~~~
Function
Constructor scope inheritance
Functions defined by the Function constructor do not inherit any scope outside the global scope (which all functions inherit).
Functions defined by Function expressions and functions defined by Function declarations are parsed only once, whereas functions defined by Function constructors are different. That is, the Function body string passed to the Function constructor is parsed each time the constructor is called.
Although Function expressions create a closure each time, the Function body is not parsed repeatedly, so Function expressions are still faster than “new Function(…) “. “. So Function constructors should be avoided as much as possible.
Call a function
Basic instructions
Defining a function does not automatically execute it. Defining a function simply gives the function a name and specifies what to do when the function is called. The calling function actually performs these actions with the given parameters.
For example, once you have defined the function square, you can call it like this:
square(5);
Copy the code
The above statement calls the function by providing the argument 5. The function returns the value 25 after executing its statement.
Functions must be in the domain from which they are called, but the declaration of functions can be promoted (appearing after the calling statement), as in the following example:
console.log(square(5));
/ *... * /
function square(n) { return n*n }
Copy the code
A function field refers to the place where a function is declared, or the entire program when a function is declared at the top level.
Call Precautions
Note that only the syntactic form above (function funcName(){}) is used. The following code is invalid.
That is, function promotion applies only to function declarations, not to function expressions.
console.log(square); // square is hoisted with an initial value undefined.
console.log(square(5)); // TypeError: square is not a function
var square = function (n) {
return n * n;
}
Copy the code
Function arguments are not limited to strings or numbers. You can also pass the whole object to a function. The show_props function (defined in Programming with objects) is an example of an object as a parameter.
Functions can be recursive, that is, functions can call themselves. For example, the following function computes factorial recursively:
function factorial(n){
if ((n == 0) || (n == 1))
return 1;
else
return (n * factorial(n - 1));
} Copy the code
You can calculate the factorial of 1-5 as follows:
var a, b, c, d, e;
a = factorial(1); // 1 is assigned to a
b = factorial(2); // 2 is assigned to b
c = factorial(3); // assign 6 to c
d = factorial(4); // 24 is assigned to d e = factorial(5); // assign 120 to e Copy the code
There are other ways to call a function. Some common situations are where a function needs to be called dynamically, or the number of arguments to the function changes, or the context in which the function is called needs to be specified as a specific object that is determined at run time.
Obviously, functions are objects themselves, so those objects also have methods (see Function). As one of these cases, the apply() method can do these things.
Summary of today’s lesson
Today the mood
Today I will learn how to declare and call function objects based on search. I hope to learn more about function scoped closures and arrow functions ~~~~ tomorrow
This article is formatted using MDNICE