Advanced JavaScript (2)

1. Definition and call of function

1.1 How to define functions

  1. Method 1 Function declaration method function keyword (named function)

    function fn(){<!-- -->}
    
  2. Method 2 function expression (anonymous function)

    var fn = function(){<!-- -->}
    
  3. Method 3 new Function()

    var f = new Function('a', 'b', 'console. log(a + b)');
    f(1, 2);
    
    var fn = new Function('parameter1','parameter2'..., 'function body')
    Notice
    /*Function inside parameters must be in string format
    The third method is inefficient and inconvenient to write, so it is less used
    All functions are instances (objects) of Function
    Functions are also objects
    */
    

1.2 Function call

/* 1. Ordinary functions */
function fn() {<!-- -->
console.log('The pinnacle of life');
}
 fn();
/* 2. Object methods */
var o = {<!-- -->
  sayHi: function() {<!-- -->
  console.log('The pinnacle of life');
  }
}
o.sayHi();
/* 3. Constructor */
function Star() {<!-- -->};
new Star();
/* 4. Binding event function */
 btn.onclick = function() {<!-- -->}; // This function can be called when the button is clicked
/* 5. Timer function */
setInterval(function() {<!-- -->}, 1000); //This function is automatically called once a second by the timer
/* 6. Execute the function immediately (self-invoking function)*/
(function() {<!-- -->
console.log('111');
})();

2.this

2.1 The this point inside the function

These this points are determined when we call the function. The difference in the calling method determines the direction of this is different

Generally points to our caller.

Please add picture description

2.2 Change the this point inside the function

2.2.1 call method

The call() method invokes an object. It is simply understood as the way to call the function, but it can change the this point of the function

Application scenario: often do inheritance.

var o = {<!-- -->
name: 'andy'
}
 function fn(a, b) {<!-- -->
      console. log(this);
      console.log(a + b)
};
fn(1,2)// At this time, this points to window, and the running result is 3
fn.call(o,1,2)//At this time, this points to the object o, the parameters are separated by commas, and the running result is 3

2.2.2 apply method

The apply() method calls a function. It is simply understood as a way to call a function, but it can change the this point of the function.

Application scenario: often related to arrays

var o = {<!-- -->
name: 'andy'
}
 function fn(a, b) {<!-- -->
      console. log(this);
      console.log(a + b)
};
fn()// At this time, this points to window, and the running result is 3
fn.apply(o,[1,2])//At this time, this points to the object o, and the parameters are passed through an array. The running result is 3

2.2.3 bind method

The bind() method will not call the function, but it can change the internal this point of the function, and return the new function generated after the original function changes this

If you just want to change the point of this and don’t want to call this function, you can use bind

Application scenario: do not call the function, but still want to change the point of this

 var o = {<!-- -->
 name: 'andy'
 };

function fn(a, b) {<!-- -->
console. log(this);
console.log(a + b);
};
var f = fn.bind(o, 1, 2); // here f is the new function returned by bind
f();//Call the new function this points to the object o parameters are separated by commas

2.2.4 The similarities and differences between call, apply and bind

  • Common point: all can change the direction of this

  • difference:

    • call and apply will call the function and change the internal this point of the function.
    • The parameters passed by call and apply are different. The parameters passed by call are separated by commas, and the parameters passed by apply are passed by arrays.
    • bind will not call the function, it can change the internal this point of the function.
  • Application Scenario

    1. call often does inheritance.
    2. apply is often related to arrays. For example, using mathematical objects to achieve the maximum and minimum values of an array
    3. bind does not call the function, but still wants to change the this point. For example, change the this point inside the timer.

3. Strict mode

3.1 What is strict mode

JavaScript provides strict mode in addition to normal mode. ES5’s strict mode is a way of adopting a restrictive variant of JavaScript that runs JS code under strict conditions.

Strict mode is only supported in browsers with versions above IE10, and will be ignored in older versions of browsers.

Strict mode makes some changes to normal JavaScript semantics:

1. Eliminate some unreasonable and imprecise parts of Javascript syntax, and reduce some weird behaviors.

2. Eliminate some unsafe aspects of code operation to ensure the safety of code operation.

3. Improve the efficiency of the compiler and increase the running speed.

4. Some grammars that may be defined in future versions of ECMAScript are disabled to pave the way for future new versions of Javascript. For example, some reserved words such as: class, enum, export, extends, import, super cannot be used as variable names

3.2 Enable strict mode

Strict mode can be applied to the entire script or to individual functions. Therefore, when using it, we can divide strict mode into two cases: enabling strict mode for scripts and enabling strict mode for functions.

  • Case 1: Enable strict mode for scripts

    • Some script scripts are in strict mode, and some script scripts are in normal mode, which is not conducive to file merging, so the entire script file can be placed in an anonymous function that is executed immediately. This creates a scope independently without affecting other
      script script file.

      (function (){<!-- -->
        //The strict mode is enabled in the current self-invoking function, and the normal mode is still outside the current function
      "use strict";
             var num = 10;
      function fn() {<!-- -->}
      })();
      //or 
      <script>
        "use strict"; //The current script tag has enabled strict mode
      </script>
      <script>
        //The current script tag does not enable strict mode
      </script>
      
  • Case 2: Enable strict mode for the function

    • To enable strict mode for a function, place the “use strict”; (or ‘use strict’; ) declaration before all statements in the function body.

      function fn(){<!-- -->
      "use strict";
      return "123";
      }
      //The current fn function has enabled strict mode
      

3.3 Changes in strict mode

Strict mode makes some changes to the syntax and behavior of Javascript.

'use strict'
num = 10
console.log(num)//use undeclared variables after strict mode
-------------------------------------------------- ------------------------------
var num2 = 1;
delete num2;//strict mode does not allow variables to be deleted
-------------------------------------------------- ------------------------------
function fn() {<!-- -->
 console.log(this); // this is undefined in functions in global scope in strict mode
}
fn();
-------------------------------------------------- --------------------------------
function Star() {<!-- -->
this.sex = 'Male';
}
// Star(); In strict mode, if the constructor is called without new, this points to undefined and if it is assigned a value, an error will be reported.
var mxy = new Star();
console.log(mxy.sex);
-------------------------------------------------- --------------------------------
setTimeout(function() {<!-- -->
  console.log(this); //In strict mode, timer this still points to window
}, 2000);

4. Higher-order functions

Higher-order functions are functions that operate on other functions, receiving functions as arguments or outputting functions as return values.

A function is also a data type, which can also be used as a parameter and passed to another parameter. The most typical is as a callback function. Similarly, functions can also be passed back as return values

5. Closure

5.1 Scope Review of Variables

Variables are divided into two types according to their scope: global variables and local variables.

  1. Global variables can be used inside functions.
  2. Local variables cannot be used outside a function.
  3. When the function finishes executing, the local variables in this scope will be destroyed.

5.2 What is a closure

A closure is a function that has access to variables in the scope of another function. The simple understanding is that a scope can access local variables inside another function.

 function fn1() {<!-- --> //fn1 is the closure function
   var num = 10;
   function fn2() {<!-- -->
       console. log(num);
 }
fn2()
 }
fn1();

5.3 The role of closure

Role: Extend the scope of the variable.

 function fn() {<!-- -->
   var num = 10;
   function fun() {<!-- -->
       console. log(num);
 }
    return fun;
 }
var f = fn();
f();

6. Recursion

6.1 What is recursion

**Recursion:** If a function can call itself internally, then this function is a recursive function. Simple understanding: the function calls itself internally, this function is a recursive function

**Note:** The function of the recursive function is the same as that of the loop. Because the recursion is prone to “stack overflow” errors (stack overflow), it is necessary to add the exit condition return.

6.2 Use recursion to find the factorial of 1~n

//Use the recursive function to find the factorial of 1~n 1 * 2 * 3 * 4 * ..n
 function fn(n) {<!-- -->
     if (n == 1) {<!-- --> //end condition
       return 1;
     }
     return n * fn(n - 1);
 }
 console. log(fn(3));

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-QVQvLyXL-1679428543187)(assets/img6-167897551259429.png)]

6.3 Use recursion to find the Fibonacci sequence

// Use recursive function to find Fibonacci sequence (rabbit sequence) 1, 1, 2, 3, 5, 8, 13, 21...
// After the user enters a number n, the rabbit sequence value corresponding to this number can be obtained
// We only need to know the first two items (n-1 n-2) of n entered by the user to calculate the sequence value corresponding to n
function fb(n) {<!-- -->
  if (n === 1 || n === 2) {<!-- -->
        return 1;
  }
  return fb(n - 1) + fb(n - 2);
}
console.log(fb(3));

6.4 Use recursion to traverse data

// We want to make a data object that can be returned by entering the id number
 var data = [{<!-- -->
   id: 1,
   name: 'Home appliances',
   goods: [{<!-- -->
     id: 11,
     gname: 'refrigerator',
     goods: [{<!-- -->
       id: 111,
       gname: 'Haier'
     }, {<!-- -->
       id: 112,
       gname: 'beautiful'
     },

            ]

   }, {<!-- -->
     id: 12,
     gname: 'Washing machine'
   }]
 }, {<!-- -->
   id: 2,
   name: 'Apparel'
}];
//1. Use forEach to traverse each object inside
 function getID(json, id) {<!-- -->
   var o = {<!-- -->};
   json.forEach(function(item) {<!-- -->
     // console.log(item); // 2 array elements
     if (item.id == id) {<!-- -->
       // console. log(item);
       o = item;
       return o;
       // 2. We want to get the data 11 12 in the inner layer, we can use the recursive function
       // There should be an array of goods and the length of the array is not 0
     } else if (item.goods & amp; & amp; item.goods.length > 0) {<!-- -->
       o = getID(item.goods, id);
     }
   });
   return o;
}