Notes on the fourth day of basic JavaScript

JavaScript Basics - day 4 notes

Understand the meaning of encapsulation, be able to realize logical encapsulation through the declaration of functions, know the characteristics of object data types, and realize simple calculation functions in combination with mathematical objects.

  • Understand the characteristics of function encapsulation
  • Master the syntax of function declaration
  • Understand what is the return value of a function
  • Know and use common built-in functions

function

Understand the encapsulation characteristics of functions and master the syntax rules of functions

Declaration and invocation

Functions can "wrap" code with the same or similar logic, and execute these wrapped code logic through function calls. The advantage of this is that it is conducive to simplifying code and facilitating reuse.

Declaration (definition)

Declare (define) a complete function, including five parts: keyword, function name, formal parameter, function body and return value

call

The declared (defined) function must be called before it can be really executed. Use () to call the function.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript Basics - Declaration and invocation</title>
</head>
<body>
  <script>
    // The simplest function is declared (defined), with neither formal parameters nor return values
    function sayHi() {
      console.log('hi~')
    }
    // Function calls, and the code logic in these functions will be executed
    // Function name ()
        
    sayHi()
    // It can be called repeatedly, any number of times
    sayHi()
  </script>
</body>
</html>

Note: the naming rules of function names are consistent with those of variables, and the semantics of function names should be guaranteed as much as possible.

Small case: Little Star

<script>
        // Function declaration
        function sayHi() {
            // document.write('hai~')
            document.write(`*<br>`)
            document.write(`**<br>`)
            document.write(`***<br>`)
            document.write(`****<br>`)
            document.write(`*****<br>`)
            document.write(`******<br>`)
            document.write(`*******<br>`)
            document.write(`********<br>`)
            document.write(`*********<br>`)
        }
        // function call
        sayHi()
        sayHi()
        sayHi()
        sayHi()
        sayHi()
    </script>

parameter

By passing parameters to the function, the function can be more flexible and changeable. The parameter can be understood as a variable.

Declare (define) a function whose function is to say hello

  • Incoming data list
  • Declaring this function requires several data to be passed in
  • Multiple data are separated by commas
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript Basics - Function parameters</title>
</head>
<body>

  <script>
    // Declare (define) a function whose function is to say hello
    // function sayHi() {
    //   console.log('Hi ~ ')
    // }
    // Call function
    // sayHi()
	

    // This function seems to be of little value unless you can say hello to different people
    // This needs to be implemented with the help of parameters
    function sayHi(name) {
      // The parameter name can be understood as a variable
      console.log(name)
      console.log('hi~' + name)
    }

    // Call sayHi function, there is more 'Xiao Ming' in parentheses
    // This is equivalent to assigning value to parameter name
    sayHi('Xiao Ming')// The result is Xiao Ming

    // Call sayHi function again. There is more 'little red' in parentheses
    // This is equivalent to assigning value to parameter name
    sayHi('Xiao Hong') // The result is Xiaohong
  </script>
</body>
</html>

Summary:

  1. There is no limit on the number of formal parameters when declaring (defining) a function. It is used when there are multiple formal parameters, separating
  2. The arguments passed by the calling function should be in the same order as the formal parameters

Formal and actual parameters

Formal parameters: when declaring a function, the parameters written in the parentheses to the right of the function name are called formal parameters

Actual parameters: when calling a function, the parameters written in the parentheses to the right of the function name are called actual parameters

Formal parameters can be understood as variables declared in this function (for example, num1 = 10). Actual parameters can be understood as assigning values to this variable

During development, try to keep the number of formal and actual parameters consistent

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript Basics - Function parameters</title>
</head>
<body>
  <script>
    // Declare (define) a function to calculate the sum of any two numbers
    // The formal parameters x and y represent any two numbers, which are two variables
    function count(x, y) {
      console.log(x + y);
    }
    // Call the function and pass in two specific numbers as arguments
    // At this time, 10 is assigned to the formal parameter x
    // At this time, 5 is assigned to the formal parameter y
    count(10, 5); // The result is 15
  </script>
</body>
</html>

Return value

The essence of a function is encapsulation (wrapping). After the logic inside the function is executed, how can the external part of the function get the internal execution result? To obtain the execution result of the internal logic of the function, you need to pass the internal execution result to the outside of the function through the keyword return. The result passed to the outside is the return value.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript Basics - Function return value</title>
</head>
<body>

  <script>
    // Define the summation function
    function count(a, b) {
      let s = a + b
      // s is the result of a + b
      // Pass s to the outside through return
      return s
    }

    // Call a function, if a function has a return value
    // Then the return value can be assigned to any external variable
    let total = count(5, 12)
  </script>
</body>
</html>

Summary:

  1. Using the return keyword in the function body can give the internal execution result to the function for external use
  2. Return can only occur once in the function, and the next line of return code will not be executed, so don't wrap the data after the return
  3. return "the current function ends immediately."
  4. The function can have no return. In this case, the default return value is undefined

Scope

Generally speaking, the name used in a piece of program code is not always valid and available, and the code range that limits the availability of this name is the scope of this name.

The use of scope improves the locality of program logic, enhances the reliability of the program, and reduces name conflicts.

global scope

It acts as an environment for all code execution (inside the entire script tag) or an independent js file

Variables within the global scope are called global variables

Local scope

The code environment within the function is the local scope. Because it is related to functions, it is also called function scope.

Variables in the local scope are called local variables

If the variable is not declared inside the function, it can be directly assigned. It is also considered as a global variable, but it is strongly not recommended

However, there is a case where the formal parameters inside a function can be regarded as local variables.

Anonymous function

Functions can be divided into named functions and anonymous functions

Anonymous function: a function without a name cannot be used directly.

Function expression

// statement
let fn = function() { 
   console.log('Function expression')
}
// call
fn()

Execute function now

(function(){ xxx  })();
(function(){xxxx}());

Execute immediately without calling. In fact, it has already been called

Multiple immediate functions are separated by semicolons

Higher order function

/* Higher order functions: take functions as parameters or return values (functions are also data types and can also be assigned values) */
/*Function: improve the logic of code, achieve high cohesion and improve performance */
        function test(a){
            console.log( a )
            return function(){alert(1111)}
        }

        let b = test()
        
// Transfer function in higher order function
      function fn(handle) {
      return handle()
       }
       console.log(fn(function () {
      return 20
    }));

console.log( a )
return function(){alert(1111)}
}

    let b = test()

//Transfer function in higher order function
function fn(handle) {
return handle()
}
console.log(fn(function () {
return 20
}));
If it can be accessed, the local part first, not the global part

Tags: Javascript Front-end programming language

Posted by rem on Thu, 08 Sep 2022 21:32:14 +0300