2021-08-05 function basis 2

3. Return value of function

  • If the return keyword is not written in the function, the function returns undefined by default

    <script>
        function f1(){
    		var a = 1;
    		var b = 2;
    	}
    	var a = f1();
    	console.log(a);
    </script>
    
  • If there is a return keyword in the function, the value after return is returned

    <script>
    	function f1(){
    		return'Huazi';
    	}
    	var a = f1();
    	console.log(a);
    </script>
    
  • If there is a return keyword in the function, but there is no value after the keyword, the return is undefined

    <script>
    	function f3(){
    		return;
        }
    	var a = f3();
    	console.log(a);
    </script>
    
  • If the function has a return, the code after return will not be executed

    <script>
    	 function f4(){
       	 	return'Yellow Crane Tower';
    		console.log(324234);
    	}
    	var a = f4();
    	console.log(a);
    </script>
    
  • If multiple values are returned after return, the last data / value is returned

    <script>
    	function f5(){
    		return 1,2,3,4,5,6;
    	}
    	var a = f5();
    	console.log(a);
    </script>
    
  • Case exercise

    Calculate the sum of 2 and 3

    <script>
    	function sum(){
    		var a = 2;
    		var b = 3;
    		var c = a + b;
    		console.log(c);
    	}
    	sum();
    </script>
    

    Enter two numbers and return the sum of two numbers

    <script>
    	var num1 = +prompt('input num1');
    	var num2 = +prompt('input num2');
    	function sum(num1,num2){
    		return num1 + num2;
    	}
    	var a = sum(num1,num2);
    	console.log(a); 
    </script>
    

    Returns the sum of all numbers between n and m

    <script>
    	function sum(n,m){
    		var a = 0;
    		for(i = n; i <= m; i++){
    			a += i;
    		}
    		return a;
    	}
    	var s = sum(1,100);
    	console.log(s);
    </script>
    

    Enter two numbers and return the maximum of the two numbers

    <script>
    	var num1 = prompt('input num1');
    	var num2 = prompt('input num2');
    	function max(num1,num2){
    		return num1 > num2 ? num1 : num2;
    	}
    	var a = max(num1,num2);
    	console.log(a);
    </script>
    

    Enter three numbers and return the maximum of the three numbers

    <script>
    	var num1 = prompt('input num1');
    	var num2 = prompt('input num2');
    	var num3 = prompt('input num3');
    	function max(num1,num2,num3){
    		return num1 > num2 ? num1 > num3 ? num1 : num3 : num2 > num3 ? num2 : num3;
    	}
    	var a = max(num1,num2,num3);
    	console.log(a);
    </script>
    

    Enter an array and return the sum of all elements in the array

    <script>
    	var arr = [1,2,3,4,5,6,7];
    	function sum(arr){
    		var sumArr = 0;   
    		for(var i = 0; i < arr.length; i++){
    			sumArr += arr[i];
    		}
    		return sumArr;
    	}
    	var a = sum(arr);
    	console.log(a);
    </script>
    

4. Scope of JavaScript function

1. Scope of variable

The valid range of variables that can be accessed in the program is divided into global variables and local variables

  • Global variables: variables that are visible in the whole page and can be freely accessed and defined outside the function
  • Local variable: the skill is visible inside the declared function, and access is not allowed outside the function Variables defined inside a function

2.Javascript local variables

Variables declared inside a function can only be accessed inside a function

<script>
    function f1(){
		var a = 1;
		console.log(a);
	}
	f1();
	// a is not defined
	console.log(a);
</script>

3.Javascript global variables

Variables declared outside a function can be used anywhere

<script>
	var a = 1;
	console.log(a);			
	function f1(){
		console.log(a);
	}			
	f1();
</script>

be careful:

  1. Variables defined inside the function are local variables, but if var is not added, they are global variables

    <script>
        function(){
        	// Declare a without adding var. A is a global variable
        	a = 1;
    	}
    	f1();
    </script>
    
  2. If the variable in the function is defined without adding var, but appears in the formal parameter, it is still a local variable

    <script>
        function(a){
        	// Declare a without adding var, but a is a formal parameter and a is a local variable
        	a = 1;
    	}
    	f1();
    </script>
    
  3. Summary:

    • If there is a variable without var inside the function, find the formal parameter first. If there is a formal parameter, it is a local variable
    • If there is no var and no formal parameter, it is a global variable

4.window object

  • In js, by default, the global variables declared by var and the global functions declared by function are mounted in window

  • In js, the properties and methods under window can be called without writing window.

  • If the variable declared in the function does not write var (global variable), it will be regarded as an attribute of window

    <script>
    	// global variable
    	var a = 1;
    	
    	//Global function
    	function(){
            //The variable in the function does not add var, and it defaults to the window attribute
    		a = 2;   
    	}
    </script>
    

5. Scope chain

Scope chain: search rules for data in js

Scope chain VS scope:

Scope is the area and scope where the variable takes effect

Scope chain describes the process of a program looking for variables

When looking for a variable, the program first looks for it from its own scope, uses it when it is found, looks up to the next level if it is not found, and looks up again if it is not found, until it finds the global scope, uses it when it is found, and reports an error if it is not found

<script>
	var a = 0;
	function fn1() {
        var a = 1;
		function fn2() {
			var a = 2;
			function fn3() {
				// var a = 3;
				console.log(a);
			}
			fn3();//Find variables in your own scope. At this time, output 3. If there are no variables in your scope, look up to the next level
		}
		fn2();//Find the upper level scope and output 2. If there are no variables in the upper level scope, look up again
	}
	fn1();//Find the upper level scope and output 1. If there is no variable in this level scope, find it in the global scope
	//Find the global scope and output 0
</script>

6. Closure

  • Global variables can be used under local scope, but the function cannot read the variables inside the function

    <script>
        //The scope chain cannot find a variable at the upper level
    	var a = 996;
    	function f1(){
        	console.log(a);
    	}
    	f1();
    	
    	//Variables inside the function cannot be read outside the function
    	function f2(){
        	var a = 996;
    	}
    	f1();
    	console.log(a);
    </script>
    
  • If you define variables inside a function without adding var and set the variables to global variables, you can access the variables inside the function from the outside of the function

    <script>
    	function f2(){
        	a = 996;
    	}
    	f1();
    	console.log(a);
    </script>
    
  • How to read local variables in a function from the outside

    1. Nest a function inside a function

      <script>
      	function f1(){
              var a = 996;
              function f2(){
                  return a;
              }
      	}
      </script>
      
    2. Internal functions refer to variables of external functions; f2 is included in f1. At this time, f2 is a search variable that can access the variables in f1 (one level up the scope chain)

    3. The external function returns the method body of the internal function; Since f2 reads the local variable in f1, the variable can be read outside f1 as long as f2 is taken as the return value

      <script>
      	function f1(){
              var a = 996;
              function f2(){
                  //Read local variables in f1
                  return a;
              }
              return f2;//Method body returned by f2 / without parentheses
      	}
      </script>
      
    4. Both external and internal functions are executed

      <script>
      	function f1(){
              var a = 996;
              function f2(){
                  //Read local variables in f1
                  return a;
              }
              return f2;//Method body returned by f2 / without parentheses
      	}
      	f1();//f1 called is the method body of f2 of return
      	f1()();//A parenthesis after the method body will execute the method body
      </script>
      
    5. Method summary

      1. Two functions nested

      2. The internal function must reference the local variable (scope chain) of the external function

      3. The external function returns the method body of the internal function (the function name is not in parentheses)

      4. Both external and internal functions should be executed (parentheses are added after the method body)

        <script>
            function f1(){
            	var a = 996;
            	function f2(){
                	return a;
            	}
            	return f2;
        	}
        	var b = f1()();
        	console.log(b);
        </script>
        
  • Concept of closure

    In the above code, f2 function is a closure. It can be understood that closure is a function nesting that can read internal variables of other functions

  • How to generate closures?

    1. Function nesting
    2. An internal function references a local variable of an external function
    3. The external function returns the method body of the internal function
    4. Both external and internal functions are executed
  • What is a closure?

    • Understanding 1: closures are nested inner functions
    • Understanding 2: objects containing referenced (external function) variables
    • Understanding 3: the so-called closure is a reference relationship, which exists in the internal function and refers to the object of the variable of the external function

Keywords: Javascript

Added by MrPixel on Sun, 02 Jan 2022 09:04:09 +0200