(Personal summary) Functions in JavaScript

Functions in JavaScript

Definition of function : A function is the basic module unit of JavaScript, containing a set of statements for code reuse, information hiding and combined calls.
Simply put: a function is to put any piece of code in a box, when I want to execute this code, I can directly execute the code in this box.

Function creation and structure

1. Function creation

In the JavaScript language, it can be created in three ways:

  • Function declaration
 //函数声明式创建函数
 function f1() {
    
    
     //需要编写的代码
 }
// function: 声明函数的关键字,表示接下来是一个函数了
// f1: 函数的名字,我们自己定义的(遵循变量名的命名规则和命名规范)
// (): 必须写,是用来放参数的位置(一会我们再聊)
// {}: 就是我们用来放一段代码的位置(也就是我们刚才说的 “盒子”)

  • Literal creation (assignment)
var f2 = function() {
    
    
    //需要编写的代码
}

  • Use the Function constructor to create (not recommended)
    var f3 = new Function('参数1','参数2',...,'函数要执行的代码')//构造函数的参数中最后一个参数为函数体的内容,其余均为函数的形参

2. Function call

The function call is actually to make the function execute (using the code in the function)

Function call is to write the function name () directly.

    f1();
    f2();
    f3();

˙Note: After defining a function, if the function is not called, then the code written in the function {} will have no meaning.

3. Function structure

The general expression of the function is:

    //函数声明
    function fn(参数[行参]){
    
    
        //函数体
    }
    fn(参数[实参])

The function includes the following 4 parts:

  • Reserved words: function
  • Function name: fn
  • Parameters: parentheses and the parameters inside the parentheses
  • Function body: curly braces and statements inside curly braces

4. Anonymous function

When a function is declared without a function name, then the function is called an anonymous function

    function() {
    
    
        //编写的代码
    }

The difference between declarative creation function and assignment creation function:
Although the calling methods of the two definition methods are the same, there are still some differences

  • Declarative function: call can be called before or after definition
    //可以调用
    fn();

    //声明式函数
    function fn(){
    
    
        console.log('我是婧婧')
    }

    //也可以调用
    fn()

  • Literal assignment function: call can only be after the defined function
    //不可以调用(会报错)
    fn();
    
    //赋值式函数
    var fn = function(){
    
    
        console.log('我是婧婧')}

    //可以调用
    fn();

Function parameters

  • We define the function and call the function, there are parentheses ()
  • Thinking about the role of parentheses ()?
  • The parentheses are where we store the parameters
  • Parameters are divided into: line parameters and actual parameters
    //声明函数
    function fn(行参写在这里){
    
    

    }
    fn(实参写在这里))

1. The role of line parameters and actual parameters

  • Line parameters

    • Variables that can be used inside the function, but not outside the function
    • Without setting a line parameter, it is equivalent to defining a variable that can be used inside the function
    • Separate parameters with commas
        function fn(a,b,c){
          
          
            //相当于在函数内部定义了a b c 三个变量,我们可以直接在函数内部使用这个三个变量
           consoloe.log( a + b +c)
        }
    
    • If there are only line parameters and no actual parameters, then use this variable inside the function without value, you will get aundefined
    • The value of the line parameter is determined by the actual parameter when the function is called
  • Arguments

    • Assign values ​​to line parameters when the function is called
    • That is to give a specific content when calling the function
        function fn(a,b,c){
          
          
            // 相当于在函数内部定义了a b c 三个变量,我们可以直接在函数内部使用这个三个变量
           consoloe.log( a + b +c)
        }
        fn(1,2,3)
    
        //这里的行参为: a,b,c
        //这里的实参为: 1,2,3
    
    
    • When the function has multiple parameters, the line parameters and actual parameters have a one-to-one correspondence

2. The relationship between the number of parameters

When the function is called, the copy of the actual parameters to the formal parameters will be completed.
When the number of actual parameters and the number of formal parameters do not match, it will cause an operation error

  • Less line reference

    • Because the parameter formulas correspond one to one in order
    • When the line reference is less than the actual parameter, then the line parameter cannot get the extra actual parameter
        function fn(a,b){
          
          
            //函数内部可以使用a 和 b
        }
    
        //调用函数
        fn(1,2,3)
    
        //本次调用传递了 三个 实参: 1 , 2 ,3 
        //1 对应的行参 为a,2对应的行参 为b,那么 3 没有跟它对应的行参,也就是函数内部没有办法已通过变量来使用3这个值
    
    
  • More line references than actual parameters

    • Because the parameter formulas correspond one to one in order
    • So the extra line parameter has no value, that is undefined
        function fn(num1, num2, num3) {
          
          
        // 函数内部可以使用 num1 num2 和 num3
        }
    
        // 本次调用的时候,传递了两个实参,100 和 200
        // 就分别对应了 num1 和 num2
        // 而 num3 没有实参和其对应,那么 num3 的值就是 undefined
        fn(100, 200)
    
  • Function parameters (arguments)

Inside the function, we always get a free argument argument.
Arguments are used to receive the actual parameters passed in when the function is called. It is designed as an array-like structure and has a length attribute, but it is not a real array, so the method corresponding to the array cannot be used.
The existence of the arguments parameter allows us to portable functions that do not need to specify the number of line parameters

function sum(){
    
    
    var sum = 0;
    var count = arguments.length;
    for(var i = 0;i < coung; i++){
    
    
        sum += arguments[i];
    }
    console.log(sum);
}





<script>
        /*
            在函数的内部有一个数据是可以不用定义就能使用的,那么这个数据就是arguments
            arguments 表示函数所有实参的集合(伪数组,像数组的集合,但是并不是数组)
            arguments有一个属性 length,表示的是函数 实参的个数

            每个实参在这个集合中都会有一个特定下标(索引),想要从这个集合中获取实参,必须通过实参对应的索引来获取,集合的索引是从0开始
            arguments[索引n] === 得到这个索引n对应的的数据
        */
        function sum() {
    
    
            // console.log(arguments[5]);
            //  从arguments集合中把每一个实参拿出来进行相加
            var sum = 0;
            // 通过for循环取出arguments结合中数据(函数的实参)
            for (var i = 0; i < arguments.length; i++) {
    
    
                // console.log(arguments[i]);
                // 把每一个实参相加
                sum += arguments[i]  
            }
            console.log(sum);
        }
        sum(1, 2, 3)
    </script>

The return value of the function (return)

  • The return statement in the function body gives the function a return value or terminates the execution of the function.
  • When the return statement is executed, the function returns immediately without executing the remaining code.
    //  终止函数的执行
    function fn() {
    
    
        console.log(1)
        console.log(2)
        console.log(3)
        
        // 写了 return 以后,后面的 4 和 5 就不会继续执行了
        return
        console.log(4)
        console.log(5)
    }

    // 函数调用
    fn()

  • The return statement is followed by the data you want to return (it can be an expression or any data type)
    function fn() {
    
    
        // 执行代码
        return 100
    }

    // 此时,fn() 这个表达式执行完毕之后就有结果出现了
    console.log(fn()) // 100
  • The function always has a return value. If there is no return statement in the function body or the return is empty, the function will return undefined in general
    function fn() {
    
    
    // 执行代码
    }

    // fn() 也是一个表达式,这个表达式就没有结果出现
    console.log(fn()) // undefined

Advantages of functions

Function is the encapsulation of a piece of code, which is called when we want to use this piece of code

[1] Encapsulate the code to make the code more concise

[2] The reusability is stronger. When realizing the repetitive function, can you just call the encapsulated one directly?

[3] The timing of code execution can be executed at any time when we want to execute it

Guess you like

Origin blog.csdn.net/weixin_43901780/article/details/107092650