Plain and simple JavaScript functions

1. Two creation methods

The writing method of functions in JavaScript is very similar to python, because there is no need to declare the type in advance, so there is no such thing as a return value. The following demonstrates the most common way of writing

/* 先来看一下函数的结构:
function 函数名(参数1, 参数2 ... , 参数n){
    函数体
    return 返回值;
}

我们来观察一下 JavaScript 中函数的特点:
1、声明的时候没有说明返回值类型
2、参数列表中每一个参数也没有指明类型(多个参数使用 , 隔开)
3、所有的函数开头均以 function 开头
4、返回值使用 return */

//现在我们按照上面的格式,实现一个功能:判断输入的字符是数字还是字母
function judge(variable) {
    
    
    if (variable >= "0" && variable <= "9") {
    
    
        return variable + " 这是一个数字";
    } else if (variable >= "a" && variable <= "z") {
    
    
        return variable + " 这是一个小写字母"
    } else if (variable >= "A" && variable <= "Z") {
    
    
        return variable + " 这是一个大写字母";
    } else {
    
    
        return variable + " 这不是数字,也不是字母";
    }
}

console.log(judge(1));
console.log(judge('a'));
console.log(judge('G'));
console.log(judge('@'));

Console output:

18



The above writing method is actually very easy to accept, and the following introduces another writing method

/* 格式:
var 函数名 = function(参数1, 参数2 ... , 参数n){
    函数体
    return 返回值;
} 

解释一下为什么可以这么写:首先在 JavaScript 中函数也是一个对象,那么当然可以通过变量赋值的形式创建,我们简化一下可以看成 var 变量名 = 值,这里值就是函数体
*/

//我们将上边的例子改写成第二种形式:
var judge = function(variable){
    
    
    if (variable >= "0" && variable <= "9") {
    
    
        return variable + " 这是一个数字";
    } else if (variable >= "a" && variable <= "z") {
    
    
        return variable + " 这是一个小写字母"
    } else if (variable >= "A" && variable <= "Z") {
    
    
        return variable + " 这是一个大写字母";
    } else {
    
    
        return variable + " 这不是数字,也不是字母";
    }
}


2. Function parameters

In this section, we will introduce knowledge points related to JavaScript function parameters. Of course, I will not talk about those things that everyone knows. What I will talk about are JavaScript-specific things.

Let's first understand a keyword arguments , the Chinese translation is parameter (s), it always points to all the parameters passed in by the caller of the current function , please note that it must be the passed parameter. The storage method of arguments is similar to an array, but remember, it is not an Array!

//我们先随便写一个例子,看看 arguments 的用法
function setArray(variable) {
    
    
    var array = [];
    //arguments.length 实际上就是传入参数的个数
    for (let i = 0; i < arguments.length; i++) {
    
    
        //获取的方式也和 Array 相似,可以通过下标访问
        array[i] = arguments[i];
    }
    return array;
}

let arguments = setArray(10, 20, 30, 40, 50);
console.log(arguments);

Console output:

19


You can see that a function with only one parameter list can also receive n parameters , which is the power of arguments. But there is a disadvantage - repeated saving parameters

For example: If there is a function (value_1, value_2, value_3), and I pass 5 parameters, namely a, b, c, d, e

value_1 corresponds to a; value_2 corresponds to b; value_3 corresponds to c; arguments correspond to a, b, c, d, e, this is repeated, if there is a keyword that can only save d and e!


For this reason, ES6 provides a new feature, introducing the rest keyword to save redundant function parameters

/* 使用 rest 格式(这里使用最常用的函数写法):
function(参数1, 参数2, ...rest) {
    函数体
    return 返回值;
} 

需要注意,rest 只能写在参数列表的最后边 */

function setArrayWithRest(variable, ...rest) {
    
    
    var array = [];
    for (let i = 0; i < rest.length; i++) {
    
    
        array[i] = rest[i];
    }
    return array;
}

var rest = setArrayWithRest(10, 20, 30, 40, 50);
//直接转换成字符串输出
console.log(rest);

This is not clear enough, here is a screenshot of IDEA (using arguments and rest respectively):

20


Browser console output:

21



3. Variables

3.1, variable scope

There is another point in the function that we need to pay special attention to, that is, the scope of variables. If the code you write conflicts with others, it may be a variable conflict. But don't worry, after reading my explanation, you will definitely gain something (hey, you are so confident)

Previously, our variables were all declared with var, so let’s talk about the scope of var first

//首先先看下面两句 console.log(variable_1) 那一句会执行?
function func1() {
    
    
    var variable_1 = "I'm variable_1, in func1";
    console.log(variable_1);					//语句 1
}

func1();
console.log(variable_1);						//语句 2

Running results (you guessed it):

22


Obviously, statement 1 is successfully executed, but variable_1 is undefined outside the function body, indicating that variable_1 is only useful inside the function body, so let’s draw a conclusion first (verify slowly, don’t rush): variables declared using var cannot be used outside the function body use



Ok, let's continue to look at the example:

function func1() {
    
    
    var variable_1 = "I'm variable_1, in func1";
    
    //函数 func1() 内写 func2()
    function func2() {
    
    
        console.log(variable_1);					//语句 1
    }
    
    //下面这两句代码都会成功嘛?
    console.log(variable_1);						//语句 2
    func2();
}

func1();

operation result:

23


It can be seen that the execution is successful, indicating that variable_1 also works in func2(), and we draw the second conclusion: the variable declared with var, whether it is the current function itself or its internal function, can be used



Moving on, we're pretty close to the truth:
function func1() {
    
    
    
    function func2() {
    
    
        //现在我们在 func2 内部定义变量
        var variable_2 = "I'm variable_2, in func2";
        console.log(variable_2);						//语句 1
    }

    //下面这两句代码都会成功嘛?
    func2();
    console.log(variable_2);							//语句 2
}

func1();

operation result:

24


Statement 1 is output normally, and statement 2 reports an error, so variable_2 cannot be used in func1(), but can only be used in func2(). We draw the third conclusion: variables declared with var cannot be used in outer functions

To sum up, we come to a conclusion: variables declared with var cannot be used outside the function body, but can be used anywhere in the function body . For example, for (var a = 0; a < 10; a++), as long as a is in the current function body, it can be used casually! Then some people may be curious, what if the variable modified with var appears outside the body of the function? We can regard an entire file as a function (hypothesis). According to the principle, this variable can be used anywhere in the file, that is, global variable


Obviously, using var is prone to variable conflicts. So ES6 added two new keywords to modify variables: let and const


The new keyword let in ES6 and its scope

Due to the space here (because there are other knowledge points to be written, you don’t like to read it after a long time), so I will be brief

Before ES6, there was no concept of block scope (that is, code blocks wrapped with {}). After ES6, we can use let to declare variables, which can only be used in the current code block, that is, they cannot be accessed outside {}

function func3() {
    
    
    for (let i = 0; i < 10; i++) {
    
    
        let variable_3 = 10;
    }

    //这回能成功输出吗?按照 let 的定义,应该是不可以的
    console.log("variable_3 = " + variable_3);
}

func3();

Running results (it is indeed impossible to output the value of variable_3, after all, its scope is only within the for statement):

25


A few knowledge points for derivation:

  • If a variable declared with let appears outside the body of a function (directly written in a non-function or code block area), it is still a global variable
  • If a variable declared with let appears at the beginning of a function , the scope of the variable is the entire function
  • Variables decorated with let are not window variables. Let’s take a look at this point first, we haven’t mentioned what is the window object yet, spoiler here, the window object is a global object of JavaScript


The new keyword const in ES6 and its scope

In other programming languages, const is used to decorate constants, and JavaScript is no exception. Before ES6, there was an unwritten rule for defining constants-variables expressed in all uppercase letters are constants (obviously, there will be problems). Since ES6, we can use const to declare constants (that is, values ​​that cannot be changed). The specific usage is as follows:

function func4() {
    
    
    const variable_4 = 100;
    console.log("variable_4 = " + variable_4);					//语句 1

    //尝试改变常量的值,编译都无法通过
    variable_4 = 200;
    console.log("改变 variable_4 的值:" + variable_4);			 //语句 2
}

func4();

Running result (Prompts Assignment to constant variable error):

26


The three ways of declaring variables, var, let, and const, are introduced above, and their scopes are also discussed in detail. Let's take a look at other knowledge points about function variables in JavaScript:



3.2. Processing mechanism for variables with the same name

//我们还是先看例子,并观察执行结果

function func5() {
    
    
    //学习了 let,我们之后尽量都用它
    let variable_5 = "outer variable";

    function func6() {
    
    
        //和外部函数相同名称的变量
        let variable_5 = "inner variable";
        console.log("func6 输出:" + variable_5);					//语句 1
    }

    func6();
    console.log("func5 输出:" + variable_5);						//语句 2
}

func5();

This time we first analyze the possible output of statement 2: according to the scope rules of let, the internal variables of func6() must not be used in func5(), so it is impossible for statement 2 to output "inner variable", so it is only possible to output "outer variable"; for statement 1, both values ​​are indeed in compliance with the regulations, but if we are a compiler, will we choose "closer", so we may choose "inner variable", let's see the running results:

27


It is indeed the same as what we analyzed, so let's summarize the processing mechanism of variables with the same name (very simple):

  • When the inner function and the outer function have variables with the same name, the inner function uses the inner variable first
  • Due to the problem of variable scope, the external function cannot access the variables of the internal function, so it can only use its own variables


3.3. Variable promotion

Maybe you can deduce the previous conclusions from other programming languages, but this is the first time you have heard of variable promotion. The JavaScript function definition has a feature, it will first scan the statement of the entire function body, and "promote" all the variables declared by **var** to the top of the function (see the example for an example)

function func7() {
    
    
    'use strict';
    var variable_6 = "Hello ";
    //使用到了未定义的变量
    console.log(variable_6 + variable_7);					//语句 1
    var variable_7 = "world!";
    console.log(variable_6 + variable_7);					//语句 2
}

//请问语句 1 会报错吗?
func7();

operation result:

28


Result analysis: Even if we enable the strict checking mode, the code can still be compiled and output normally. This is because although variable_7 is declared at the end of the function body, according to the principle of variable promotion, when executing func7(), all The variable declaration mentions the top, which is equivalent to variable7 being declared, but without assignment, all will display undefined

But please note that according to my test, variable promotion is invalid for variables declared by let and const , so for normal use, I recommend that whether you use var or let, the variable declaration should be placed at the top of the function to prevent trouble for yourself!

Guess you like

Origin blog.csdn.net/qq_52174675/article/details/122636391