Getting started with front-end JavaScript-day04

(Creating is not easy, thank you, your support is the biggest motivation for me to move forward, if it is helpful to you after reading it, please leave your footprints)

Table of contents

function

Why do you need functions

function usage

function declaration syntax

Function name naming convention

function call syntax

function body 

function parameter

declaration syntax 

call syntax 

function return value

scope

Variable Access Principles

anonymous function

function expression 

Execute the function immediately


function

1 Why do we need functions

Function: function is a code block
designed to perform a specific task Description : A function can "wrap" code with the same or similar logic, and execute the "wrapped" code logic through a function call. The advantage of doing this is that it is beneficial to simplify the code and facilitate reuse. For example, the alert(), prompt() and console.log() we used earlier are some js functions , but they have been encapsulated, and we use them directly


2 function usage

function declaration syntax

 For example:

Function name naming convention

It is basically the same as the variable naming. Try to
keep the camel case as small as possible.
The prefix should be a verb.
Naming suggestion: Common verb conventions

function call syntax

Note: The declared (defined) function must be called to be executed, use () to call the function

example


The alert() and parseInt() we used to use are essentially function calls followed by parentheses 

function body 

The function body is the constituent part of the function, which is responsible for "wrapping" the same or similar code, and the code in the function body will not be executed until the function is called. The function code of the function must be written in the function body.

<!-- 1. 封装一个函数,计算两个数的和 -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        function getSum()
        {
            let num1=+prompt('第一个数')
            let num2=+prompt('第二个数')
            document.write(num1+num2)
        }
        getSum()
    </script>
</body>
</html>

function parameter

Thinking: Such a function can only calculate 10 + 20, the function of this function is very limited


Solution: Pass the number to be calculated into the function
Conclusion:
If the function needs the caller to pass in data to complete the function, then you need to use a function with parameters
, which can greatly improve the flexibility of the function

declaration syntax 

Parameter list
        Pass in data list
        Declare that this function needs to pass in several data
        Multiple data are separated by commas

single parameter


multiple parameters

call syntax 

 When calling a function, write as many data as you need to pass in, separated by commas

Formal parameters : When declaring a function, the parameters written in parentheses on the right side of the function name are called formal parameters (formal parameters). Actual parameters: When
calling a function, the parameters written in parentheses on the right side of the function name are called actual parameters (actual parameters).
Formal parameters can be understood as variables declared in this function (such as num1 = 10). Actual parameters can be understood as assigning
values
​​​​to this variable. ('11') are essentially function call parameters

<!-- 需求:学生的分数是一个数组,计算每个学生的总分
分析:
①: 封装一个求和函数
②: 传递过去的参数是一个数组
③: 函数内部遍历数组求和 -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        //封装函数
        function getArrSum(arr)
        {
            let sum=0
            for(let i = 0;i<arr.length;i++)
            {
                sum+=arr[i]
            }
            document.write(sum)
        }
        let arr = [1,2,3,4,5,6]
        getArrSum(arr)
    </script>
</body>
</html>

The web page appears as:                                                  

function return value

The concept of a function with a return value:
when a function is called, the function will return a result, which is a function with a return value

In fact, we have already touched a lot of functions with return values:


It's just that these functions are built-in at the bottom of JS. We can use them directly
. Of course, some functions have no return value


Therefore, it is necessary to set whether the return value is required or not according to the requirements.

When a function needs to return data, use the return keyword

grammar


How to use it?  

Details:
Use the return keyword in the function body to transfer the internal execution results to the outside of the function. Use
return. The code after return will not be executed again , and the current function will be terminated immediately, so the data after return should not be written in a new line.
The return function can be without return. In this case, the default return value of the function is undefined

<!-- 求任意2个数中的最大值, 并返回 -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        function max(num1,num2)
        {
            return num1>num2?num1:num2
        }
        let num1=+prompt('第一个数为')
        let num2=+prompt('第二个数为')
        let a=max(num1,num2)
        document.write(a)
    </script>
</body>
</html>

scope

Generally speaking, the name used in a piece of program code is not always valid and usable, and the code scope 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.

 In JavaScript, according to different scopes, variables can be divided into:

Variable Access Principles

As long as it is code, there must be at least one scope. The
local scope written inside the function . If there are functions in the function, then another scope access principle
can be born in this scope : first local when it can be accessed, and the local is not looking for the global.

Scope chain : take the approach of the principle of proximity to find the final value of the variable

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        let a = 1
        function fn1() 
        {
            let a = 2
            let b = '22'
            fn2()
            function fn2() 
            {
                let a = 3
                fn3()
                function fn3()
                {
                    let a = 4
                    document.write(`a<br>`) //a的值 ?
                    document.write(b) //b的值 ?
                }
            }
        }
        fn1()
    </script>
</body>
</html>

The web page appears as:                                      

anonymous function

A function without a name cannot be used directly.
How to use:
        function expression
        executes the function immediately

function expression 

Assigning an anonymous function to a variable and calling it by the variable name we call this a function expression

grammar:


transfer:


The formal parameters and actual parameters of the function are used in the same way as the named function

Execute the function immediately

Scenario introduction: Avoid polluting syntax between global variables
:


Note: Multiple immediate execution functions need to be separated by ;, otherwise an error will be reported

Guess you like

Origin blog.csdn.net/weixin_73295475/article/details/131410054