Knowledge system of Web front end development engineer_ 22_JavaScript core

Posted by hush2 on Wed, 15 Dec 2021 17:42:40 +0100

1, Closure

Both global variables and local variables have their own advantages, but they also have their own shortcomings. The advantage of global variables is that they can be reused, but they are easily polluted (note that all forms of global variables are prohibited in general companies). Although local variables will not be polluted, they cannot be reused.

To solve this problem, you need to define an exclusive and reusable variable for a function. Only the function itself can be used. When other functions are not available, closures are used!

Closure is a programming method that reuses variables and protects variables from being polluted. After the outer function is called, the scope object of the outer function is referenced by the inner function and cannot be released, forming a closure object. The use of closures is divided into three steps:

(1) Wrap the variables to be protected with outer functions and inner functions that use variables

(2) Inside the outer function, return the inner function object.

(3) Call the outer function and catch the returned inner function object with variables.

<script>
    // 1. Wrap the variables and inner functions to be protected with outer functions
    function mother() {
      var total = 1000;
      // 2. The outer function returns the inner function object
      return function (money) {
        total -= money;
        console.log(`Yes ${money}Yuan, left ${total}element`);
      }
    }
    // 3. Call the outer function and catch the returned inner function with variables
    var pay = mother();
    pay(100);//900 left
    // The value of total here does not interfere with the value defined in the mother function
    total = 0;
    pay(100);//800 left
    pay(100);//700 left
  </script>

However, closures also have some shortcomings. The memory function returned by closures occupies more memory space than ordinary functions (the function scope object of the outer function); therefore, if a closure is no longer intended to be used, it should be released in time.

Save the variable of the inner function = null, which releases both the inner function object and the scope object of the outer function.

2, Object oriented

A large amount of data will be saved in the program in the future. If a large amount of data is managed randomly, it is very easy to make mistakes! And it's inconvenient to use. Therefore, in the future, the program will manage a large amount of data in an object-oriented way. In the program, multiple attributes and functions describing a thing will be stored in an object structure, and then a name will be given.

Three characteristics of object-oriented: encapsulation, inheritance and polymorphism.

1. Packaging

Encapsulation refers to creating an object to centrally store the attributes and functions of one of the real things, which is extremely convenient for the management and maintenance of a large amount of data. There are three ways to package:

(1) {}, commonly used when creating an object, the format is as follows

var Object name={
      Attribute name: Attribute value, 
      ... : ... , 
      Method name: function(){ ... }
    }

When accessing properties or methods in an object, use -- object Property name -- or -- object Method name () -- OK. However, when {} is directly used for encapsulation, an error will be reported when you want to use another attribute name of the object in the object's own method! The xxx attribute name is undefined. There are two ways to solve this problem:

a: write the name of the dead object Property name, but once the object name changes and some object names are written dead in the object, an error will be reported! Therefore, this method is not recommended.

b: in the future, this will be added to the methods in the object as long as you want to use the current object's own properties or other methods. This is built-in in each function. It does not need to be created. It is directly used to point to the current function being called.

<script>
    var lilei = {
      sname: "Li Lei",
      sage: 11,
      intr: function () {
        // ----------this here refers to Previous object----------
        console.log(`I am ${this.sname},I am ${this.sage}year`);
      }
    }
    console.log(lilei.sage);
    lilei.intr();
    lilei.sage++;
    console.log(lilei.sage);
    lilei.intr();
  </script>

(2) new in the following format

var Object name=new Object();

Tip: function == new Function()

Forcibly add new properties and methods to empty objects, - object name New attribute = attribute value; -- object name New method = function() {... This. Property name...}  --. It can be seen that the underlying objects in js are associative arrays.

When accessing members, the standard writing method is -- object name / array name ["member name"] --, which is abbreviated as -- object name / array name Member name --; If the member name is a number, you can only use -- object name / array name [number] - if the member name is a variable, you can only use -- object name / array name [variable] - without quotation marks.

Note: if you forcibly assign a value to a nonexistent location, you will not report an error, and the attribute will be added automatically; If you forcibly access the value of a nonexistent location, no error will be reported, but undefined will be returned.

<script>
    var lilei = {};
    lilei["sname"] = "lilei";
    lilei.sage = 11;
    console.log(lilei);
    console.log(lilei.className); //Undefined forcibly accesses the value of a nonexistent location. No error will be reported, but undefined will be returned
    for (var Attribute name key in lilei) {
      console.log(`Property name: ${Attribute name key},Attribute value: ${Attribute name key}`);
    }

    var lilei = [];
    // The underlying objects in js are associative arrays
    lilei.sname = "Lilei";
    lilei["sage"] = 11;
    console.log(lilei);
    console.log(lilei["className"]); //undefined
    for (var Attribute name key in lilei) {
      console.log(`Property name: ${Attribute name key},Attribute value: ${Attribute name key}`);
    }
  </script>

Example: clone an object

<script>
    var liang = {
      sname: "Jiusheng God of war",
      sage: 1000,
      sex: "male"
    }
    // Clone
    function clone(old) {
      // 1. Create an empty object and wait
      var now = {};
      // 2. Attribute name in epoch object
      for (var oldlist in old) {
        // 3. Get the original attribute value of the original object, and then add the attribute with the same name
        var oldvalue = old[oldlist];
        now[oldlist] = oldvalue;
      }
      return now;
    }
    var liang2 = clone(liang);
    console.log(liang2);
    console.log(liang2 == liang);
  </script>

(3) Use constructor

Only one object can be created at a time with {}. If you want to create multiple objects with the same structure, the code will be a lot of repetition, which is extremely inconvenient for future maintenance. When you want to repeatedly create multiple objects with the same structure but different contents, use constructors.

Four functions of new
1. Create a new empty object and wait
2. Let the child object inherit the prototype object of the constructor (inheritance only)
3. Call the constructor, replace this with a new object, and add the specified attributes to the new object by forced assignment
4. Return the address of the new object

Define constructor:

function Type name(Formal parameter 1, Formal parameter 2, ...){
   //The specified properties to be added to the new object in the future
   this.Attribute name=Formal parameter 1;
   this. xxx = xxx; 
   this.Method name=function(){ ... this.Attribute name ... }
}

Repeatedly create multiple objects with the same structure with the constructor:

var Object name=new Type name(Argument value 1, Argument value 2, ...)

Example: define the constructor to specify the unified structure of the student type object

<script>
    // Define constructor
    // ---------Here this refers to the new object---------
    function Student(sname, sage) {
      this.sname = sname;
      this.sage = sage;
      this.intr = function () {
        console.log(`My name is ${this.sname},I this year ${this.sage}year`);
      }
    }
    // Repeatedly create multiple objects with the same structure but different contents with the constructor
    var lilei = new Student("Li Lei", 45);
    var hmm = new Student("Mei Mei Han", 30);
    console.log(lilei);
    lilei.intr();
    console.log(hmm);
    hmm.intr();
  </script>

Links to previous JavaScript advanced blog posts:

JavaScript core (I)

Topics: Javascript Front-end ECMAScript