function

Function expression

A function expression is another way of defining a function.

  • Define method: Assigns the definition of a function, anonymous function, to a variable.
  • Call a function expression by adding () to the variable name, not the function name plus ().
  // Define the function
  var foo = function fun (){
      console.log(1);
  }
  // Call the function
  fun();  // Console output undefined error
  foo();  // This function is successfully called, indicating that anonymous functions are used
Copy the code

The data type of the function

  • Function is a separate data type Function(contained in object)
  • Since a function is a data type, it can participate in other programs
    • A function can be called in another function as an argument to another function.
      / / timer
      // A function is a data type that can be used as an argument to another function
      setInterval(function(){
          console.log(1);
      },1000);
    Copy the code
    • You can return a function as a return value from within a function
      function fn(b){
          var a = 10;
          return function(){ alert(a + b); }}Copy the code

The arguments object

All functions have a built-in arguments object, which stores all arguments passed. Arguments is a pseudo-array, so you can iterate over it.

  • The number of arguments to a function may differ from the number of parameters. All arguments are stored in an array object of arguments class inside the function.
  // Define a function
  function sum(a,b){
      return a + b;
  }

  // The number of arguments to a calling function may differ from the number of parameters
  console.log(sum(1));  The default value is undefined, undefined + 1 = NaN, undefined + 1 = NaN;
  console.log(sum(1.2)); / / 3
  console.log(sum(1.2.3.4)); / / 3

  // The function has a arguments object inside that accepts all arguments
  // Arguments access is similar to array arr, using subscripts
  function fun() {
      console.log(arguments); / / the Arguments (6) [6]
      console.log(arguments.length); / / 6
  }
  // Call the defined function
  fun(1.2.3.4.5.6); 
Copy the code
  • Example: Define a summation function that returns itself if one argument is passed, returns their sum if two arguments are passed, compares the first two arguments and returns the sum with the third argument if three arguments are passed, and returns an error if four or more arguments are passed.
  function sum(a,b,c){
    switch(arguments.length){
        case 1:
            return a;
        case 2:
            return a + b;
        case 3:
            return a > b ? a + c : b + c;
        default:
            // Tell the user that the number of arguments passed is incorrect
            // The simulation console reported an error
            throw new Error("No more than 3 parameters"); }}console.log(sum(1));  / / 1
console.log(sum(1.2)); / / 3
console.log(sum(1.2.3)); / / 5
console.log(sum(1.2.3.4)); / / an error
Copy the code

Function recursive

  • Inside a function, the function itself can be called by its name.
  • Recursion too many times is prone to error: the maximum computational capacity of the computer is exceeded.
  • Example: Output the value of a Fibonacci sequence. Fibonacci: The last item is the sum of the first two. 1,1,2,3,5,8,13,21,34,55…
  function fbo(a) {
    if(a == 1 || a == 2) {return 1;
    }else {
        return fbo(a - 1) + fbo(a - 2); }}console.log(fbo(1));
  console.log(fbo(2));
  console.log(fbo(3));
  console.log(fbo(4));
Copy the code

scope

The extent to which a variable can function

  • Function scope: If a variable is defined inside a function, it can only be accessed inside the function, not outside the function. The function is the scope of the variable definition.
  • Block-level scope: Any structure in a pair of curly braces {} belongs to a block, and all variables defined within this block are not visible outside the code block.
  • Before ES5, there was no concept of block-level scope, only function scope. At this stage, JavaScript can be considered to have no block-level scope.

Variables are divided into two categories according to their scope

  • Global variable: in a broad sense, is also a local variable, defined in the global variable, scope is global, in the entire JS program anywhere can be accessed.
  • Local variables: When a function is called, memory is allocated to execute the function and declare local variables. When the function is finished, this area of memory is immediately freed. (Formal parameters of a function are also local variables.)
  • The difference between the two: variables are destroyed when they exit the scope, and global variables are destroyed when they close the web page or browser.

Scope of parameters and functions

  • Formal parameters of a function are also local variables. The parameters of the function are also local variables within the function itself and can only be used inside the function. They are not defined outside the function.
  • A function defined within a function can only be called within the scope of the function that defined it.
  // Incorrect writing
  function outer(a) {
    a = 1;
    console.log(a);
    function inner() {
      console.log("I am inner");
    }
    // Correct: call inner() from here;
  }
  // Call the function
  outer(1);
  inner(); // The console will report an error, undefined
Copy the code

Scope chains and shadowing effects

  • As long as it is code, there is at least one scope, namely: global scope. Whenever there is a function in the code, that function constitutes another scope. If there are functions within a function, then another scope can be created within that scope.

  • Scope chain: to list all such scopes, there can be a structure -> function inside the chain pointing to the function outside

    • Case study:
        // F1 function: 0-level chain
        function f1() {
      
          // The num variable in the f1 function: 1 chain
          var num = 123;
      
          // The f2 function in the f1 function: 1 level chain
          function f2() {
            // The num variable in the f2 function: 2-level chain
            console.log(num);
          }
          
          f2();
        }
      
        // Num variable: 0 chain
        var num = 456;
        f1();
      Copy the code

      Illustration of case:

  • Shading effect

    • Procedure in case of a variable, use scope when find order, different levels of function are likely to define variables of the same name, a variable when use, will from his first layer to find the variable scope, if the current layer is not variable definitions according to the order from this layer to find, in turn until you find the first variable definitions (if not found, The console will say is no defined.). During the whole process, the effect of inner variables obscuring outer variables occurs, which is called “obscuring effect”.
    • Case study:
      /* Cannot find the case when executing the console.log(num) in the f2() function; If num is found in the f2() function (2 levels chain), it will output if num is found; If it does not exist, it will be found in the f1() function (1 level chain) and output num; If it doesn't exist, output num(currently in the outermost :0 chain); If it still doesn't exist, the program will report an error in the console. Masking effect: The nearest one will mask the farther */
          // Num variable: 0 chain
          var num = 456;
      
          // F1 function: 0-level chain
          function f1() {
      
            // The num variable in the f1 function: 1 chain
            var num = 123;
      
            // The f2 function in the f1 function: 1 level chain
            function f2() {
              var num = 78;
      
              // The num variable in the f2 function: 2-level chain
              console.log(num);
            }
            
            f2();
          }
      
          f1();
      Copy the code

The effect of not writing the var keyword

  • If you want to define a new variable inside a function, if you don’t use the var keyword,Equivalent to a defined global variable. If the global has the same identifier, it will be affected by variables inside the function, and the local variables will contaminate the global variables.
      // Global variables
      var a = 1;
      function fun() {
        a = 2;
        console.log(a); / / 2
      }
      // Local variables contaminate global variables.
      console.log(a); / / 2
    Copy the code

Preliminary analysis

  • The execution of javascript code is performed by the javascript parser in the browser. Javascript parser executes javascript code in two processes: pre-parsing and code execution.
  • Pre-parsing process:
      1. Promoting the declaration of a variable to the top of the current scope will only promote the declaration, not the assignment.
      1. Promoting a function’s declaration to the top of the current scope promotes only the declaration, not the call.
      1. Promote var first, then function
  • Javascript execution process: after pre-parsing, according to the new code order, from the top down in accordance with the established rules to execute JS code.

Variable declaration promotion

  • In the process of promotion, only the declaration process is promoted, but the variable assignment is not promoted, which is equivalent to the variable definition is not assigned, and the undefined value is stored in the variable.
  • Therefore, there will be a phenomenon in JS, in the earlier call after the definition of a variable, no error, only use undefined value.

Function declaration promotion

  • During the execution of the pre-parsed code, the function definition process is already executed at the beginning, and once the function is defined successfully, the function can be called directly afterwards.
  • Therefore, there will be a phenomenon in JS, in the previous call after the definition of the function, no error, and can normally execute the code inside the function.

Ascending order

During the pre-parsing process, the var variable declaration is promoted first, and then the function declaration is promoted.

  • Suppose the variable name and function name are the same

    • The later promoted function name identifier overrides the first promoted variable name.
    • When the call identifier appears in subsequent code, it is the function definition, not undefined, that is inside.
      // Simulate the preparsing process
      Var fun = undefined; var fun = undefined; Function fun(a) {a = 1; return a; } * /
      Logon fun(a) {a = 1; logon fun(a) {a = 1; return a; } */ */ */ */
      console.log(fun);
      
      // If you call a function before it is defined, no error will be reported
      var b = fun();
      console.log(b); / / 1
      // Function definition
      function fun() {
          return 1;
      }
      
      // Assign a value to fun, and fun becomes Numner
      var fun = 1;
      console.log(fun); / / 1
    
      Uncaught TypeError: fun is not a function Uncaught TypeError: fun is not a function Uncaught TypeError: Fun is not a function Uncaught TypeError: Fun is not a function * /
      var c = fun();
      console.log(c); // Uncaught TypeError: fun is not a function
    Copy the code
    • If the identifier is called after the source code function and the variable definition, the function name overwrites the variable name once, and the result is that the new value overwrites the function value when the variable is assigned, then the identifier is called again with the new value stored in the variable.
  • Suggestion: Do not write the same identifier for the variable name or function name to avoid overwriting.

Promotion of function expressions

  • During preparsing, the function expression is promoted by variable declaration, not function declaration. There is an undefined inside the promoted variable. Prior to the function method call, the data type prompts an error.
   Var foo; In this case, the internal store is: undefined; therefore, the function expression method is used, and the function cannot be called before the function definition procedure, and an error */ will be reported
   foo();  // Uncaught ReferenceError: fun is not defined

   var foo = function (){
       console.log(5);
   }
Copy the code
  • Suggestion: When defining a function, it is best to use the function keyword to define the method, so that the function declaration promotion can take effect forever.

The function declares the application of promotion

  • Function declaration promotion can be used to reorder the code, putting large sections of definition at the end of the code, but without affecting the execution of the code.

IIFE self-calling functions

  • IIFE: Immediately – Invoked function expression, called the immediately invoked function expression, also called since

Calling a function means that the function is called as soon as it is defined.

  • Function call: the variable name of the function or function expression is followed by the () operator.
  • The function name definition does not allow immediate self-invocation. The function expression definition allows immediate execution. The reason is that during the function expression definition, a function is reduced to an expression, followed by the () operator, which can be executed immediately.
  // Function name +() cannot implement immediate execution of self-call
  function fun (){
      console.log(1); } ();// The function expression form can be executed immediately
  var foo = function (){
      console.log("halou"); } ();// Output: halou without calling statement

Copy the code
  • Inspiration: If you want to implement IIFE, you can find a way to dwarf functions into expressions.

The function is dwarfed into an expression

Functions can be dwarfed into expressions to achieve self-calling.

  • The way a function is dwarfized into an expression allows it to perform some operation, that is, precede the function with some operator. (4)
    • Mathematical operators: + – ()
    • Logical operator:! The operation
      + function fun (){
          console.log(1); / / 1} (); -function fun (){
          console.log(1); / / 1} (); (function fun (){
          console.log(1); / / 1}) (); !function fun (){
          console.log(1); / / 1} ();Copy the code
  • The IIFE structure closes the scope of functions. Functions cannot be called from outside the structure.
  • The most commonly used IIFE operator is the () operator, and functions can be anonymous without writing their names.

  (function fun (a){  // The input receives the value passed by the argument
        console.log(a);  // Hello}) ("Hello!");  // Since the function cannot be called externally and no arguments can be passed, the arguments are written inside the parentheses
Copy the code