Closure and prototype chain in js

Closure

  1. What is a closure

    Functions are nested functions, and the inner function can access the variables of the outer function, it is called a closure

 (function(){
          var a = 1;
          function fn() {
              var b = 2;
              var sum = b + a;
              console.log(sum); 
          }  
          fn();
        })()

-The fn function calls the variable a in the external function

  1. The function of
    closures, the biggest function of closures is to hide variables. A major feature of closures is that internal functions can always access the parameters and variables declared in the external function in which they are located, even after the external function is returned, based on this The feature javaScript can realize the existence of private variables

  2. The advantages of closures
    can isolate the scope and will not cause global pollution of variables

  3. Disadvantages:
    Closures stay in memory for a long time, resulting in memory leaks.
    Solution: Reset the exposed closure variables to null

Prototype chain

When we call a method or property of an object, we will first find the method on the object instance, if there is one, we will call it, if not, we will use the object's proto (prototype) to look up, if we find it, we will execute the call. It will search on the prototype of the created object, that is, on the prototype of the object. If it is found, the call will be executed. Otherwise, it will continue to search in prototype.proto. If not, go to prototype.proto.prototype to search until the query is found. null is the top of the prototype chain

  • proto:
    Explicit prototype
  • Prototype:
    implicit prototype When an object is used as a constructor function, it will be used as the proto of the newly constructed function

Guess you like

Origin blog.csdn.net/t5_5_5_5_5_7_7/article/details/109722811