当前位置:网站首页>JS --- JS function and scope (II)

JS --- JS function and scope (II)

2022-07-06 15:22:00 Cirrod

1、 function

function : It encapsulates a code block that can be repeatedly called and executed . A lot of code can be reused through this code block .

1.1、 Use of functions

The function is used in two steps : Declare and call functions

① Declare functions

// Declare functions

function  Function name (){

// Function body code 

}

function Is the key to declare a function , Must be in lowercase

Because functions are generally defined to implement a function , So we usually name the function verb , such as getSum

② Call function

// Call function

 Function name (); // Execute the function body code by calling the function name 

Don't forget to add parentheses when calling

formula : Function does not call , Don't do it yourself

Be careful : Declaring the function itself does not execute code , Function body code is executed only when the function is called .

1.2、 Encapsulation of functions

Function encapsulation is to encapsulate one or more functions through functions , It only provides a simple function interface to the outside world

1.3、 The parameters of the function

1.3.1、 Formal parameters and actual parameters

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

Parameters explain
Shape parameter Formal parameters When defining a function Parameters passed I don't know what it is at present
Actual parameters The actual parameters When the function is called Parameters passed Arguments are passed to formal parameters

Function of parameters : Some values cannot be fixed inside a function , We can pass different values when calling the function through parameters

// Function declaration with arguments

function  Function name ( Shape parameter 1,  Shape parameter 2 ,  Shape parameter 3...) { //  You can define as many parameters as you want , Separate with commas 

//  The body of the function }

// Function call with parameters

 Function name ( Actual parameters 1,  Actual parameters 2,  Actual parameters 3...);

for example : Use the function to find the sum of any two numbers

// Declare functions

function getSum(num1,num2){

console.log(num1+num2)

}

// Call function

getSum(1,3) //4

getSum(6,5) //11

When a function is called, the argument value is passed to the formal parameter

Formal parameters are simply understood as : Undeclared variables

Multiple parameters of an argument and a formal parameter are separated by commas (,) Separate ,

1.3.2、 The number of formal and actual parameters does not match

Number of parameters explain
The number of arguments is equal to the number of formal parameters Output the correct result
The number of arguments is more than the number of formal parameters Only get the number of formal parameters
The number of arguments is less than the number of formal parameters Multiple formal parameters are defined as undefined, The result is NaN
function sum(num1, num2) {

console.log(num1 + num2);

}

sum(100, 200); // 300, The number of formal and actual parameters is equal , Output the correct result 



sum(100, 400, 500, 700); // 500, There are more arguments than formal parameters , Only get the number of formal parameters 



sum(200); //  The number of arguments is less than the formal parameter , Multiple formal parameters are defined as undefined, The result is NaN

Be careful : stay JavaScript in , The default value of a parameter is undefined

1.3.3、 Summary

Functions can take parameters or no parameters

When you declare a function , In the parentheses of the function name is the formal parameter , The default value of the formal parameter is undefined

When you call a function , In the parentheses of the function name is the argument

Multiple parameters are separated by commas

The number of formal parameters can not match the number of arguments , But the results are unpredictable , We try to match

1.4、 The return value of the function

1.4.1、return sentence

sometimes , We would want the function to return the value to the caller , At this time, by using return Statement can be implemented .

return The syntax format of the statement is as follows :

//  Declare functions 

function  Function name (){

...

return  The value to be returned ;

}

// Call function

 Function name (); //  At this point, you can call the function to get the function body return  Value after 

In the use of return When the sentence is , Function will stop executing , And returns the specified value

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

// Declare functions

function sum(){

...

return 666;

}

// Call function

sum(); //  here  sum  The value of is equal to 666, because  return  Statement will return the value after itself to the caller 

1.4.2、return Terminate function

return The code after the statement is not executed

function add(num1,num2){

// The body of the function 
return num1 + num2; //  Be careful :return  After the code does not execute 

alert(' I will not be executed , Because there are  return');

}

var resNum = add(21,6); //  Call function , Pass in two arguments , And pass  resNum  Receive function return value 

alert(resNum); // 27

1.4.3、return The return value of

return Only one value can be returned . If you separate multiple values with commas , Subject to the last one

function add(num1,num2){

// The body of the function 

return num1,num2;

}

var resNum = add(21,6); //  Call function , Pass in two arguments , And pass  resNum  Receive function return value 

alert(resNum); // 6

1.4.4、 Summary

All functions have a return value

If there is return , Then return to return Value after

without return, Then return to undefined

1.4.5、 difference

break、continue、return The difference between

break : End the current loop body ( Such as for、while)

continue : Jump out of this cycle , Continue with next cycle ( Such as for、while)

return : You can not only exit the loop , Can also return return Value in statement , At the same time, you can also end the code in the current function body

1.4.5、 practice

1. Use the function to find the maximum of any two numbers

function getMax(num1, num2) {

return num1 > num2 ? num1 : num2;

}

console.log(getMax(1, 2));

console.log(getMax(11, 2));

2. Find an array [5,2,99,101,67,77] The maximum value in

// Define a function to get the maximum number in the array

function getMaxFromArr(numArray){

var maxNum = 0;

for(var i = 0; i < numArray.length;i++){

if(numArray[i]>maxNum){

maxNum = numArray[i];

}

}

return maxNum;

}

var arrNum = [5,2,99,101,67,77];

var maxN = getMaxFromArr(arrNum); // This argument is an array 

alert(' The maximum value is ' + maxN);

3. Create a function , Realize the addition, subtraction, multiplication and division 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(a,b){

var arr = [a + b, a - b, a * b, a / b];

return arr;

}

var result = count(a,b);

console.log(result)

1.5、arguments Use

When we are not sure how many parameters are passed , It can be used arguments To get . stay JavaScript in ,arguments In fact, it is a built-in object of the current function . All functions have a built-in arguments object ,arguments Object stores all the arguments passed .

arguments It stores the passed arguments

arguments The display form is a pseudo array , So you can traverse . Pseudo arrays have the following characteristics

①: have length attribute

②: Store data by index

③: Without array push , pop Other methods

// Function declaration

function fn() {

console.log(arguments); // It stores all the passed arguments 

console.log(arrguments.length); // 3

console.log(arrguments[2]); // 3

}

// Function call

fn(1,2,3);

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)); // 9

console.log(maxValue(12, 4, 9)); // 12

Function calls another function

Because each function is a separate block of code , Used to complete special tasks , Therefore, it is often used when functions call each other . The specific demonstration will be shown in the following function exercise .

1.6、 Function exercises

1. Using function encapsulation , Flip any array

function reverse(arr) {

var newArr = [];

for (var i = arr.length - 1; i >= 0; i--) {

newArr[newArr.length] = arr[i];

}

return newArr;

}

var arr1 = reverse([1, 3, 4, 6, 9]);

console.log(arr1);

2. Using function encapsulation , Sort the array – 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[j+1]) {

     var temp = arr[j];

     arr[j] = arr[j + 1];

     arr[j + 1] = temp;

}

}

}

return arr;

}

3. Enter a year , Determine if it's a leap year ( Leap year : Can be 4 Divide and cannot be 100 Integers , Or can be 400 to be divisible by )

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 , Output the current year 2 Days of the month , If it's a leap year , be 2 Month is 29 God , If it's a normal year , be 2 Month is 28 God

function backDay() {

var year = prompt(' Please enter the year :');

if (isRun(year)) { // Calling a function requires parentheses 

alert(' What you entered ' + year + ' It's a leap year ,2 Month has 29 God ');

} else {

alert(' What you entered ' + year + ' It's not a leap year ,2 Month has 28 God ');

}

}

backDay();

// A function of whether it is a leap year

function isRun(year) {

var flag = false;

if (year % 4 === 0 && year % 100 !== 0 || year % 400 === 0) {

flag = true;

}

return flag;

}

1.7、 Two ways to declare functions

1.7.1、 Custom function mode ( Name the function )

Use function keywords function Custom function mode .

// Declaration definition method

function fn() {...}

// call

fn();

Because there's a name , So it is also called named function

The code that calls the function can be placed in front of the declared function , It can also be placed after the declared function

1.7.2、 Function expression mode ( Anonymous functions )

The use of function expression is as follows :

// This is a function expression , Anonymous functions end with a semicolon

var fn = function(){...};

// The way it's called , The function call must be written below the function body

fn();

Because the function has no name , So it is also called anonymous function

This fn Stored inside is a function

The code of the function call must be written after the function body

2、 Scope

Generally speaking , The names used in a piece of program code are not always valid and available , The scope of the code that defines the usability of the name is the scope of the name . The use of scope improves the locality of program logic , Enhance the reliability of the program , Reduced name conflicts .

JavaScript (ES6 front ) There are two kinds of scopes in :

Global scope

Local scope ( Function scope )

2.1、 Global scope

The environment that acts on all code execution ( Whole script The label inside ) Or an independent js file

2.2、 Local ( function ) Scope

Act on the code environment within the function , It's a local scope . Because it has something to do with functions , So it is also called function scope

2.3、JS There is no block-level scope

Fast scope by {} Include

In other programming languages ( Such as java、c# etc. ), stay if sentence 、 A variable created in a loop statement , Only in Ben if sentence 、 Used in this loop statement , Like the one below Java Code :

if(true){

int num = 123;

System.out.println(num);    // 123

}

System.out.println(num);        //  Report errors 

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

if(true){

int num = 123;

System.out.println(num);    // 123

}

System.out.println(num);        // 123

3、 Scope of variable

stay JavaScript in , Depending on the scope , Variables can be divided into two types :

Global variables

local variable

3.1、 Global variables

Variables declared under the global scope are called global variables ( Variables defined outside functions )

Global variables can be used anywhere in the code

In global scope var Declared variables Global variable

Under special circumstances , Don't use... In functions var Declared variables are also global variables ( Not recommended )

3.2、 local variable

Variables declared under local scope are called local variables ( A variable defined inside a function )

Local variables can only be used inside the function

Inside the function var The declared variable is a local variable

The formal parameters of a function are actually local variables

3.3、 difference

Global variables : It can be used anywhere , It will only be destroyed when the browser is closed , So it takes up more memory

local variable : Use only inside functions , When its code block is executed , Will be initialized ; After the contemporary code block runs , Will be destroyed , Therefore, it saves more memory space

4、 Scope chain

Just the code , There is at least one scope

What is written inside a function is called a local scope

If there are functions in the function , Then a scope can be created in this scope

According to this mechanism that external function variables can be accessed in internal functions , Use chain search to determine which data can be accessed by internal functions , It's called the scope chain

// Scope chain : Internal functions access variables of external functions , Chain search is used to determine which value to take , This structure is called scope linked list

var num = 10;

funtion fn() { // External function 

var num = 20;

function fun() { // Internal function 

console.log(num); // 20 , Level-1 access 

}

}

Scope chain : Take the principle of proximity to find the final value of the variable .

5、 Pre parse

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

console.log(num); //  What's the result ?
// Will report a mistake  num is undefined

console.log(num); //  What's the result ?
var num = 10;

// undefined

// Name the function ( Custom function mode ): If we put function call on function declaration

fn();                //11

function fn() {

console.log('11');

}

// Anonymous functions ( Function expression mode ): If we put function call on function declaration

fn();

var fn = function() {

console.log('22'); //  Report errors 

}

// Equivalent to executing the following code

var fn;

fn(); //fn No assignment , Have no this , Report errors 

var fn = function() {

console.log('22'); // Report errors 

}

JavaScript The code is created by JavaScript Parser to execute .JavaScript The parser is running JavaScript There are two steps to code : Pre parsing and code execution .

Pre parse :js The engine will turn js Everything in it var also function Promote to the front of the current scope

Code execution : From top to bottom JS sentence

Pre parsing only happens when you pass var Defined variables and function On . Learning pre parsing can let us know why accessing the value of a variable before it is declared is undefined, Why can a function be called before it is declared .

5.1、 Variable pre parsing ( Variable Promotion )

Variable pre parsing is also called variable promotion 、 Function enhancement

Variable Promotion : The declaration of the variable will be promoted to the top of the current scope , The assignment of variables does not increase

console.log(num); //  What's the result ?

var num = 10;

// undefined

// Equivalent to executing the following code

var num;        //  The variable declaration is promoted to the top of the current scope 

console.log(num);

num = 10;        //  The assignment of variables does not increase 

5.2、 Function pre parsing ( Function enhancement )

Function enhancement : The declaration of the function will be promoted to the top of the current scope , But it doesn't call the function .

fn();                //11

function fn() {

console.log('11');

}

5.3、 Solve the problem of function expression declaration and call

For function expression declaration calls, you need to remember : The function expression call must be written below the function declaration

// Anonymous functions ( Function expression mode ): If we put function call on function declaration

fn();

var fn = function() {

console.log('22'); //  Report errors 

}





// Equivalent to executing the following code 

var fn;

fn(); //fn No assignment , Have no this , Report errors 

var fn = function() {

console.log('22'); // Report errors 

}

5.4、 Pre analysis exercise

The pre parsing part is very important , You can go through the following 4 An exercise to understand .

Pink The teacher's video explanation pre analysis :JavaScript Basic grammar -dom-bom-js-es6 New syntax -jQuery- Data visualization echarts Dark horse pink Basic video tutorial for teachers (500 Multi set ) continued _ Bili, Bili _bilibili

// practice 1

var num = 10;

fun();

function fun() {

console.log(num);    //undefined

var num = 20;

}

//  The end result is  undefined

The above code is equivalent to performing the following operations

var num;

function fun() {

var num;

console.log(num);

num = 20;

}

num = 10;

fun();

// practice 2

var num = 10;

function fn(){

console.log(num);        //undefined

var num = 20;

console.log(num);        //20

}

fn();

//  The end result is  undefined 20

The above code is equivalent to performing the following operations

var num;

function fn(){

var num;

console.log(num);

var num = 20;

console.log(num);

}

num = 10;

fn();

// practice 3

var a = 18;

f1();



function f1() {

var b = 9;

console.log(a);

console.log(b);

var a = '123';

}

The above code is equivalent to performing the following operations

var a;

function f1() {

var b;

var a

b = 9;

console.log(a);    //undefined

console.log(b);    //9

a = '123';

}

a = 18;

f1();


// practice 4

f1();

console.log(c);

console.log(b);

console.log(a);

function f1() {

var a = b = c = 9;

//  amount to  var a = 9; b = 9;c = 9; b and c There is no var Statement , When the global variable looks 

//  A collective statement  var a = 9,b = 9,c = 9;

console.log(a);

console.log(b);

console.log(c);

}

The above code is equivalent to performing the following operations

function f1() {

var a;

a = b = c = 9;

console.log(a);    //9

console.log(b);    //9

console.log(c);    //9

}

f1();

console.log(c);    //9

console.log(b);    //9

console.log(a);    // Report errors  a It's a local variable 

原网站

版权声明
本文为[Cirrod]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131318484876.html