Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the use of JavaScript function and scope

2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the relevant knowledge of "what is the use of JavaScript function and scope". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. Function

Function: encapsulates a block of code that can be repeatedly called for execution. A large amount of code can be reused through this code block.

1.1. The use of functions

The use of a function is divided into two steps: declaring a function and calling a function

① declares function / / declares function name () {/ / function body code}

Function is the keyword that declares the function and must be lowercase

Since a function is usually defined to implement a function, we usually name the function as a verb, such as getSum

② calls function / / calls function name (); / / executes function body code by calling function name

Don't forget to add parentheses when calling

Formula: if the function is not called, it will not be executed.

Note: declaring the function itself does not execute the code, and the function body code is executed only when the function is called.

1.2, function encapsulation

The encapsulation of a function is to encapsulate one or more functions in the way of a function, providing only a simple function interface.

1.3, parameter 1.3.1, formal parameter and actual parameter of the function

When you declare a function, you can add some parameters in parentheses after the function name, which are called formal parameters, and when you call the function, you also need to pass the corresponding parameters, which are called arguments.

Parameter description formal parameter function the parameter passed when the formal parameter function is defined currently does not know what the parameter is actually the parameter argument is passed to the formal parameter when the parameter function is called

The function of parameters: some values cannot be fixed inside the function. We can pass different values through parameters when calling the function.

/ / function declaration with parameters function function name (parameter 1, parameter 2, parameter 3.) {/ / any number of parameters can be defined, separated by commas / / function body} / / function call function names with parameters (argument 1, argument 2, argument 3.)

For example, use the function to find the sum of any two numbers.

/ / declare the function function getSum (num1,num2) {console.log (num1+num2)} / / call the function getSum (1mai 3) / / 4getSum (6pm 5) / / 11

The actual parameter value is passed to the formal parameter when the function is called.

The formal parameter is simply understood as: a variable that does not need to be declared

Multiple parameters of arguments and formal parameters are separated by commas (,)

1.3.2. The number of parameters that do not match the number of parameters indicates that the number of parameters is equal to the number of parameters. Output the correct result. The number of parameters is more than the number of parameters. The number of parameters that is less than the number of parameters is defined as undefined, and the result is NaNfunction sum (num1, num2) {console.log (num1 + num2);} sum (100,200) / / 300, the number of parameters is equal to the number of arguments, and the correct result is sum (100,400,500,700); / / 500, the number of parameters is more than that of parameters, only the number of parameters is sum (200); / / the number of parameters is less than that of parameters, and the more parameters are defined as undefined, and the result is NaN.

Note: in JavaScript, the default value for formal parameters is undefined

1.3.3. Summary

Functions can be with or without arguments

When declaring a function, there are formal parameters in the parentheses of the function name, and the default value of the formal parameter is undefined

When a function is called, the parentheses in the function name are the arguments

Multiple parameters are separated by commas

The number of formal parameters can not match the number of actual parameters, but the result is unpredictable. We try to match.

1.4. the return value of the function is 1.4.1, return statement

Sometimes we want the function to return the value to the caller, which can be done by using the return statement.

The syntax format of the return statement is as follows:

/ / declare function name () {... The value to be returned by return;} / / call the function name (); / / you can get the value after return in the function body by calling the function at this time

When using the return statement, the function stops execution and returns the specified value

If the function does not have return, the returned value is undefined

Function add (num1,num2) {/ / function body return num1 + num2; / / Note: the code after return does not execute alert ('I will not be executed because it is preceded by return');} var resNum = add (21 Magi 6); / / calls the function, passes in two arguments, and receives the function return value alert (resNum) through resNum; / / 271.4.2, return terminates the function

The code after the return statement is not executed

Function add (num1,num2) {/ / function body return num1 + num2; / / Note: the code after return does not execute alert ('I will not be executed because it is preceded by return');} var resNum = add (21 Magi 6); / / call the function, pass in two arguments, and receive the function return value alert (resNum) through resNum; / / 271.4.3, the return value of return

Return can only return one value. If multiple values are separated by commas, the last one shall prevail

Function add (num1,num2) {/ / function body return num1,num2;} var resNum = add (21Power6); / / call the function, pass in two arguments, and receive the function return value alert (resNum) through resNum; / / 61.4.4, summary

All functions have return values.

If there is a return, the value after return is returned

If there is no return, undefined is returned.

1.4.5, difference

The difference between break, continue and return

Break: ends the current loop body (such as for, while)

Continue: jump out of this cycle and continue with the next cycle (e.g. for, while)

Return: you can not only exit the loop, but also return the value in the return statement, and end the code in the current function.

1.4.5, exercise

1. Using function to find the maximum value of any two numbers

Function getMax (num1, num2) {return num1 > num2? Num1: num2;} console.log (getMax (1,2)); console.log (getMax (11,2))

two。 Find the maximum value in the array [5, 2, 99, 101, 67, 77]

/ / define a function function getMaxFromArr (numArray) {var maxNum = numArray [0]; for (var I = 0; I) that gets the maximum number in the array

< numArray.length;i++){ if(numArray[i]>

MaxNum) {maxNum = numArray [I];}} return maxNum;} var arrNum = [5pjong 2je 99 maxim 101g 67j 77]; var maxN = getMaxFromArr (arrNum); / / this argument is an array alert ('maximum is' + maxN).

3. Create a function to add, subtract, multiply and divide between two numbers, and return the result

Var a = parseFloat (prompt ('Please enter the first number'); var b = parseFloat (prompt ('Please enter the second number'); function count (aMaginb) {var arr = [a + b, a-b, a * b, a / b]; return arr;} var result = count (aMagneb); console.log (result) 1.5, the use of arguments

When we are not sure how many parameters are passed, we can use arguments to get them. In JavaScript, arguments is actually a built-in object of the current function. All functions have a built-in arguments object, and all arguments passed are stored in the arguments object.

Arguments stores the passed arguments.

The arguments presentation is a pseudo array, so it can be traversed. Pseudo arrays have the following characteristics

①: with length attribute

②: store data as an index

③: push, pop and other methods without arrays

/ / function declaration function fn () {console.log (arguments); / / all passed arguments console.log (arrguments.length) are stored in it; / / 3 console.log (arrguments [2]); / / 3} / / function call fn

For example, use the function to find the maximum value of any number.

Function maxValue () {var max = arguments [0]; for (var I = 0; I

< arguments.length; i++) { if (max < arguments[i]) { max = arguments[i]; } } return max;}console.log(maxValue(2, 4, 5, 9)); // 9console.log(maxValue(12, 4, 9)); // 12函数调用另外一个函数 因为每个函数都是独立的代码块,用于完成特殊任务,因此经常会用到函数相互调用的情况。具体演示在下面的函数练习中会有。 1.6、函数练习 1.利用函数封装方式,翻转任意一个数组 function reverse(arr) { var newArr = []; for (var i = arr.length - 1; i >

= 0; iMel -) {newArr [newArr.length] = arr [I];} return newArr;} var arr1 = reverse ([1,3,4,6,9]); console.log (arr1)

two。 Sort the array by function encapsulation-bubble sort.

Function sort (arr) {for (var I = 0; I)

< arr.length - 1; i++) { for (var j = 0; j < arr.length - i - 1; j++) { if (arr[j] >

Arr [juni1]) {var temp = arr [j]; arr [j] = arr [juni1]; arr [juni1] = temp;} return arr;}

3. Enter a year to determine whether it is a leap year (leap year: divisible by 4 and not integer by 100, or divisible by 400)

Function isRun (year) {var flag = false; if (year% 4 = = 0 & & year% 100! = = 0 | | year% 400 = 0) {flag = true;} return flag;} console.log (isRun (2010)); console.log (isRun (2012))

4. The user enters the year and outputs the number of days in February in the current year. If it is a leap year, February is 29 days. If it is a normal year, February is 28 days.

Function backDay () {var year = prompt ('Please enter year:'); if (isRun (year)) {/ / call the function with parentheses alert ('the' year + 'you entered is a leap year, February has 29 days');} else {alert ('the' year + 'you entered is not a leap year, there are 28 days in February');} backDay () / / function function isRun (year) {var flag = false; if (year% 4 = 0 & & year% 100! = = 0 | | year% 400 = 0) {flag = true;} return flag;} 1.7, two declaration methods of function 1.7.1, custom function (named function)

Use the function keyword function to customize the function method.

/ / declare definition method function fn () {...} / / call fn ()

It is also called a named function because it has a name.

The code that calls the function can be placed either in front of or after the declared function

1.7.2, function expression (anonymous function)

The way to use function expressions is as follows:

/ / this is the way the function expression is written. The anonymous function is followed by a semicolon ending var fn = function () {...}; / / the function call must be written to fn () under the function body.

Because a function does not have a name, it is also called an anonymous function

What is stored in this fn is a function

The code for the function call must be written after the function body.

2. Scope

Generally speaking, the name used in a piece of program code is not always valid and available, and the scope of the code that limits the availability of the name is the scope of the name. The use of scope improves the locality of program logic, enhances the reliability of the program, and reduces name conflicts.

There are two scopes in JavaScript (before ES6):

Global scope

Local scope (function scope)

2.1. Global scope

The environment that acts on all code execution (inside the entire script tag) or a separate js file

2.2, local (function) scope

The code environment that acts within the function is the local scope. Because it has something to do with the function, it is also called function scope.

2.3.The JS has no block-level scope

The block scope is included by {}

In other programming languages (such as java, c #, etc.), variables created in if statements and loop statements can only be used in this if statement and this loop statement, such as the following Java code:

If (true) {int num = 123; System.out.println (num); / / 123} System.out.println (num); / / error report

There is no block-level scope in JS (before ES6)

If (true) {int num = 123; System.out.println (num); / / 123} System.out.println (num); / / 1233, scope of the variable

In JavaScript, variables can be divided into two types, depending on the scope:

Global variable

Local variable

3.1, global variables

Variables declared in the global scope are called global variables (variables defined outside the function)

Global variables can be used anywhere in the code

Variables declared by var under global scope are global variables

In special cases, variables that are not declared with var within a function are also global variables (not recommended)

3.2. Local variables

Variables declared in the local scope are called local variables (variables defined within the function)

Local variables can only be used within the function

The variables declared by var inside the function are local variables

The formal parameter of a function is actually a local variable.

3.3. Difference

Global variables: can be used anywhere and will only be destroyed when the browser is closed, so it takes up memory.

Local variable: used only within the function, it is initialized when the code block is executed; after the contemporary code block is run, it is destroyed, thus saving more memory space

4. Domain chain

As long as it's code, there's at least one scope.

What is written inside the function is called the local scope

If there is a function in the function, then another scope can be created in this scope.

According to the mechanism that internal functions can access external function variables, chain search is used to determine which data can be accessed by internal functions, which is called scope chain.

/ / scope chain: the internal function accesses the variables of the external function and uses the chain search method to decide which value to take. This structure is called scope chain table var num = 10 funtion fn () {/ / external function var num = 20; function fun () {/ / internal function console.log (num); / / 20, level-by-level access}}

Scope chain: use the nearest principle to find the final value of the variable.

5. Pre-analysis

First, let's take a look at a few pieces of code and the results:

Console.log (num); / / what is the result? / / will report an error num is undefinedconsole.log (num); / / what is the result? Var num = 10; / / undefined// naming function (custom function mode): if we put the function call on top of the function declaration fn (); / / 11function fn () {console.log ('11');} / anonymous function (function expression mode): if we put the function call on top of the function declaration, fn () Var fn = function () {console.log ('22'); / / error} / / equivalent to the execution of the following code var fn;fn (); / / fn is not assigned, without this, error var fn = function () {console.log (' 22'); / / error}

The JavaScript code is executed by the JavaScript parser in the browser. The JavaScript parser runs JavaScript code in two steps: pre-parsing and code execution.

Pre-parsing: the js engine promotes all var and function in the js to the forefront of the current scope

Code execution: execute JS statements from top to bottom

Pre-parsing occurs only on variables and function defined by var. Learning pre-parsing can let us know why the value of the access variable is undefined before the variable is declared, and why the function can be called before the function is declared.

5.1. Variable pre-analysis (variable promotion)

Variable preresolution is also called variable lifting, function lifting.

Variable promotion: the declaration of the variable will be promoted to the top of the current scope, and the assignment of the variable will not be promoted

Console.log (num); / / what is the result? Var num = 10; / / undefined// is equivalent to executing the following code: var num; / / variable declaration is promoted to the top of the current scope console.log (num); num = 10; / / the assignment of the variable does not increase 5.2, function pre-parsing (function promotion)

Function promotion: the declaration of the function is promoted to the top of the current scope, but the function is not called.

Fn (); / / 11function fn () {console.log ('11');} 5.3. resolve the function expression declaration call problem

For function expression declaration calls, you need to remember that function expression calls must be written below the function declaration

/ / Anonymous function (function expression): if we put the function call on top of the function declaration fn (); var fn = function () {console.log ('22'); / / error} / / equivalent to the execution of the following code var fn;fn (); / / fn has no assignment, no this, error var fn = function () {console.log (' 22'); / / error} 5.4, pre-parsing exercise

The pre-analysis part is very important and can be understood through the following four exercises.

Teacher Pink's video explanation pre-analysis: https://www.bilibili.com/video/BV1Sy4y1C7ha?p=143

/ / practice 1var num = 10 × fun (); function fun () {console.log (num); / / undefined var num = 20;} / / the final result is undefined

The above code is equivalent to doing the following

Var num;function fun () {var num; console.log (num); num = 20;} num = 10 undefined var num fn (); / / practice 2var num = 10 politics function fn () {console.log (num); / / undefined var num = 20; console.log (num); / / 20} fn (); / / the final result is undefined 20

The above code is equivalent to doing the following

Var num;function fn () {var num; console.log (num); num = 20; console.log (num);} num = 10 var fn (); / / practice 3var a = 18 var F1 (); function F1 () {var b = 9; console.log (a); console.log (b); var a = '123;}

The above code is equivalent to doing the following

Var a var function F1 () {var b; var a b = 9; console.log (a); / / undefined console.log (b); / / 9 a = '123;} a = 18 var F1 (); / / practice 4f1 (); console.log (c); console.log (b); console.log (a); function F1 () {var a = b = c = 9; / equivalent to var a = 9; b = 9 X c = 9 There is no var declaration before b and c, when global variables read / / collective declaration var a = 9, console.log (a); console.log (b); console.log (c);}

The above code is equivalent to doing the following

Function F1 () {var a; a = b = c = 9; console.log (a); / / 9console.log (b); / / 9console.log (c); / / 9} F1 (); console.log (c); / / 9console.log (b); / / 9console.log (a) / / error an is a local variable, "what is the use of the JavaScript function and scope?" so much for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report