5. Scope and recursion

1. Scope

  1. The concept of scope: variable or function or data or function, area of ​​action, area of ​​effect, area that can be used
  2. Classification of scope:
    • Global scope: Statements that do not belong to any function are called global scope. Variables in the global scope are called global variables.
    • Local scope: The area belonging to a function is called local scope. Variables in local scope are called local variables.
  3. Access rules for data between scopes (after scope nesting)
    • The parent scope cannot use data inside the child scope (the parent cannot access the child)
    • The child scope can use the data inside the parent scope (the child can take the parent)
      var a = 10;
      function fn(){
              
              
          var b = 20;
          console.log(a);		// 10
          console.log(b);		// 20
      }
      fn();
      console.log(a);		// 10
      console.log(b);		// Error: b is not defined
      
  4. After multi-level scope nesting, the reading and writing rules of variables
    • read (use):
      • First search in its own scope, use it and stop searching if you find it
      • If not found, look up the upper scope in turn
      • If any layer is found, use it and stop searching
      • I didn’t find it until the top layer, and reported an error!
    • Write (assign):
      • First search in its own scope, modify and stop searching if found
      • If not found, look up the upper scope in turn
      • If any layer is found, modify it and stop searching
      • I didn’t find it until the top level, just declare it as a global, and then modify it! (in non-strict mode, in strict mode, an error is reported)
  5. Characteristics of variables in different scopes
    • Global variables: follow the global environment, always exist in memory, occupy memory
    • Local variables: According to the local environment, the local scope is created, the variable exists, the local scope ends, the variable is deleted, and memory is saved
    • Suggestion: Use less globals as much as possible, use anonymous functions to generate a large new scope, and wrap the data and multiple functions to be used again
      ;(function(){
              
              
          var a = 10;
          function box1(){
              
              
              console.log(a);		// 10
          }
          function box2(){
              
              
              a = 20;
              console.log(a);		// 20
          }
          function box3(){
              
              
              console.log(a);		// 20
          }
          box1();
          box2();
          box3();
      })();
      

2. Statement improvement

  • The so-called statement promotion means that when the js parser parses the js code, it will first advance the variable declaration and function declaration in the current scope to the beginning of the scope for execution. This is to create the corresponding space in memory in advance , so that the program can be used directly in the future.
  • However, this is actually an existing bug in the js language. The advantage of early declaration is very small. On the contrary, when there is no concept of block-level scope, it will cause pollution of various scope spaces. So in the new features of the later version ES6, variable declaration promotion is prohibited.
  1. hoisting of declared variables
    • The variables declared by var will be declared at the beginning of the scope in advance, and assigned in place
      console.log(a);		// undefined
      var a = 10;
      console.log(a);		// 10
      
  2. Hoisting of Declared Functions
    • The function declared by function will be promoted to the beginning of the scope as a whole
      console.log(fn);		// function fn(){...}
      function fn(){
              
              
          console.log(1)
      }
      console.log(fn);		// function fn(){...}
      
  3. When var meets function
    • Assignment creation function: var fn = function(){}
      • Variables are promoted, functions are not promoted
        console.log(fun);			// undefined
        var fun = function(){
                  
                  
            console.log(2)
        }
        console.log(fun);			// function(){...}
        
    • When the variable name of var is the same as the function name of function, var is promoted first, so function takes effect
      • Note: Duplicate names are not allowed!
        console.log(b);		// function b(){...}
        var b = 20;
        function b(){
                  
                  
            console.log(3);
        }
        console.log(b);		// 20
        

3. Recursion

  1. Recursion: Inside a function, execute itself. Abusing recursion will cause a phenomenon similar to an infinite loop, causing program crashes, computer crashes, and memory overflow
    • Use the idea of ​​recursion to solve problems in the program, cooperate with the end statement of the function, and jump out of recursion when appropriate
    • Even normal recursion consumes a lot of performance
    • Use as little as possible when you have to use it, and don’t use it when you can use it as little as possible
  2. hand over:
    • self-perpetuating process
  3. Return to:
    • The process of continuously returning data to the outside
  4. Use recursion to calculate factorial, such as: 5! = 5 4 3 2 1
// 已知:
// 5! = 5 * 4 * 3 * 2 * 1
// 5! = 5 * 4!
//          4! = 4 * 3!
//                   3! = 3 * 2!
//                            2! = 2 * 1!
//                                     1
// 可推算计算任意数的阶乘公式为:
// fn(n) = n * fn(n-1);
// ...
// fn(5) = 5 * fn(4);
// fn(4) = 4 * fn(3);
// fn(3) = 3 * fn(2);
// fn(2) = 2 * fn(1);
// 计算最小数字1的阶乘为:
// fn(1) = 1;
function fn(n){
    
    
	if(n === 1){
    
    
		return 1;
	}else{
    
    
		return n * fn(n-1);
	}
}
console.log( fn(5) );		// 120

4. Object introduction

  1. Object: a description of objective things, the process of describing objective things in the form of logical data

    • Unordered data packaging, object object, flag is{}
    • Packing of ordered data, array object, flag is[]
  2. the nature of the object (composition)

    • key-value pairs. Key (key) and value (value) correspond one-to-one and appear in pairs
    • Colons are used to connect keys and values, and commas are used to separate key-value pairs. pseudocode:{ 颜色:红色, 身高:180, 体重:150, 发型:板寸 }
  3. The meaning (function) of the object: storing data, programming

  4. object creation

    • Literal:var obj = {}
    • Constructor:var obj = new Object()
  5. In any case, the two objects are not equal; if they are equal, it means that they are one object.

    var obj1 = {
          
          };
    var obj2 = new Object();
    var obj3 = {
          
          }
    var obj4 = obj1;
    console.log(obj1);		// {}
    console.log(obj2);		// {}
    
    console.log(obj1 === obj2);		// false
    console.log(obj1 === obj3);		// false
    console.log(obj4 === obj1);		// true
    
  6. object manipulation syntax

    • Dot syntax: when an object's property is a concrete value
    • Bracket syntax: when the property of the object is a variable
      var a = "world";
      var obj = {
              
              
          title:"对象的操作",
          number:18,
          [a]:"啊哈哈哈"
      }
      var str = "number";
      console.log( obj.str );			// undefined
      console.log( obj[str] );		// 18
      console.log( obj.a );			// undefined
      console.log( obj.world );		// 啊哈哈哈
      console.log( obj["title"] );	// 对象的操作
      console.log( obj[title] );		// Error: title is not defined
      
  7. object operation

    var person = {
          
          name:"张三", age:18};
    
    • increase:
      person.sex = "男";
      person["sex"] = "男";
      
    • delete:
      delete person.age;
      delete person["age"];
      
    • change
      person.sex = "女";
      person["sex"] = "女";
      
    • check
      console.log(person.name)
      console.log(person["name"])
      
  8. Classification of Objects (Understanding)

    • host object: window,document
    • Local object: Constructor, you need to execute new to get the specific object: Object, Number, String,Boolean
    • Built-in objects: officially provided objects that can be used directly:Math

5. Practice

  1. Write a function that uses recursion to solve
    • When n is an even number, call the function to find 1/2+1/4+...+1/n
    • When n is an odd number, call the function to find 1/1+1/3+...+1/n
  2. Use recursion to find the greatest common divisor of two numbers
  3. Use recursion to find the nth digit of the Fibonacci sequence (1, 1, 2, 3, 5, 8, 13, 21, ...)

Guess you like

Origin blog.csdn.net/weixin_41636483/article/details/116140104