function

1. Function introduction

1, objects,

Concepts: Projection of real “concepts” into the computer world (programming).

Therefore, if you want to understand objects, you must first look for the “concept” of realization in life, which depends on the cognition of “people”.

Concrete entities: everyday objects, cats, dogs, tables, chairs, houses, cars…

Generally “static”, noun

2, functions,

Concept: Model things in the real world and their relationships with each other, focusing on causality, i.e. inputs and outputs. Create mathematical models.

3, methods,

Concept: A method is a way of solving a problem that has several steps. The word method is for the “human” mind, whereas functions are abstract concepts with definite inputs and outputs.

Explanation:

4. Understanding of functions

If you want to understand functions, you need to know what non-functions are.

Function or non-function, you need to know how people deal with problems in the real world. What is an algorithm?

Programming is used to solve problems, according to different needs will produce different problems!

Typical “How many steps are there to put an elephant in the fridge?”

In fact, you can just say, “In the summer, in order to keep the watermelon spoilage, you need to put it in the refrigerator. This example of a practical need might be easier to understand

A more rational analysis:

1, Find the watermelon 2, pick up the watermelon 3, find the refrigerator 4, go to the refrigerator 5, open the refrigerator drawer 6, open the refrigerator drawer 7, close the refrigerator drawer 8, put the watermelon 9, close the refrigerator doorCopy the code

Why “rational” analysis? Because in real life, no one has such a complicated thinking process. Obviously, such a process is “for the computer”, and such “statements” with strict routines and steps can solve a practical problem are called “algorithms” for solving problems.

⚠️ The above is just a superficial personal opinion 😅

What if one of these questions is called, “How to Put a watermelon in the fridge?”

Assuming that “Zhang SAN” does not know this concept (what is called putting watermelon in the refrigerator), he has to explain, and the process of explanation is the “demonstration” of the algorithm.

If you need to explain the “algorithm” of the above 9 steps to solve a real problem to “Joe” every time, it would be stupid and inefficient, so you only need to tell Joe

This question = this step or these steps = the answer to this question

That way, when it comes time to put the watermelon in the fridge, you don’t have to show off the “long” steps

You just tell John, John, put the watermelon in the fridge.

Tell me to order,command

What if, instead of watermelon, you need to put it in the fridge… What about the ice cream?

Just change “watermelon” to “ice cream.

5. JavaSript functions

In javascript, all elements are objects

Functions can be objects

Functions can encapsulate some code, some functionality, and you can call the function when you need it

Such as

console.log( "I am a One"  )
console.log( "I am a two."  )
console.log( "I am a three")

//console output:I am a one. I am a two. I am a threeCopy the code

I need to think of it as a function that does something fixed, and I need to encapsulate it and I can actually encapsulate it

// encapsulates a function called PrintToConsole
function PrintToconsole(){
    console.log( "I am a One"  );
    console.log( "I am a two."  );
    console.log( "I am a three");
}
// Call the function
PrintToConsole(); 


//console output:I am a one. I am a two. I am a threeCopy the code

The main purpose of using a function is to reuse it and reduce coupling so that it can be modified later. Storing the contents of a function is like storing the contents of a variable (remember the concept of a variable; a variable is also like a container).


2. Create a function object

How to create a function:

Common creation: Object oriented

2. Use function declarations: functional

3. Function expression: variable expression

2.1. Common Creation

Grammar:

varThe function name =new Function(a);Copy the code

Example:

// Create a function object fun
var fun = new Function(a);// Test its type
console.log("Type of fun =" + typeof(fun));

// console output:Fun of type =function
Copy the code

⚠️ specifies that Function creates fun, of type Function, and that this “variable” is of type Function

▶Example: Enter information to the console in the common creation mode

var fun = new Function(Console. log('Hello this is my first function '););
fun();

//console output:Hello is my first functionCopy the code

Notes and Instructions:

  • The code wrapped into a function is not executed immediately; it is just stored in it
  • To execute, you must call a function object, calling the function object syntax:Function object name ()
  • When a function is called, the wrapped code in the function executes the call several times and the execution several times in sequence

Functions, because they are also objects, can be used as objects. Function objects have all the functions of different objects, but are more powerful than normal functions

/* fun.hello is equivalent to the property of the function object, but it is not good to declare functions like this

var fun = new Function(Console. log('HEllo this is my first function '););

// Functions can be used as objects because they are also objects
fun.hello = "Hello";
console.log( fun.hello) ;

// console output:helloCopy the code

2.2. Use function declarations

Grammar:

functionThe function name ([parameter1The parameter2The parameter3.. Parameter N]) {statement... }Copy the code

Example:

// Use function declarations to create a function (just like normal programming languages declare functions)

function fun2() {}console.log( fun2 );
// console.log(fun2()); // undefined
Copy the code

Console output:

Fun2 () is a function object whose structure is fun2

f fun2(){
}
Copy the code

And fun2() is the body of the function, so there’s nothing there so it’s undefined

At this point, there is no content because the function you just declared did not add anything

The following is an encapsulated form that also contains statements

function fun2() {
  console.log("This is my second function.");
}

Copy the code

Console output:

🙋♂️ why didn’t the result come back? Again, wrapped functions need to be called.

function fun2() {
	console.log("This is my second function.");
}
fun2(); // Function call
Copy the code

⚠️ Note: function calls need to add ()


2.3. Use functional expressions

Grammar:

varThe function name =function ([parameter1The parameter2The parameter3.. Parameter N]) {statement... }Copy the code

Example:

// Use function expressions to create functions

// To use a function expression, write an anonymous function and assign it to a variable named xyz
var fun3 = function (){
  console.log("I'm code wrapped inside an anonymous function.");
};

fun3();

//console output:I'm the code wrapped inside an anonymous functionCopy the code

summary

The way functions are created//1.
var fun = new Function(a);//2
function fun2() {}//3
var fun3 = function(){};Copy the code

⚠️ Precautions

var fun = new Function(Console. log('HEllo this is my first function '););
fun();
// --------------------

/ / to Function (" XXX "); Where XXX is the command output to the console
// For this, since console.log() is a function that returns a string, it is equivalent to
function fun2() {
 console.log("This is my second function.");
}
fun2();
Copy the code
// Function declaration
function fun01() {
    console.log("Console. log(' This is a function created with function declarations ');");
}
fun01();
// Function expression
var fun02 = function () {
    console.log("Console. log(' This is a function created with a function expression ')");
};
fun02();
// Function object
var fun = new Function("Console. log(' This is a function created using a function object ');");
fun();
Copy the code

Console results:

console.log('This is a function created with a function declaration');
console.log('This is a function created with a function expression'This is a function created using a function objectCopy the code

⚠️ The difference between using function declarations and function expressions can be understood simply as function declarations are functions, while function expressions “assign” functions to variables.


3. Function usage

First, function parameters

🚀T- Defines a function that sums two numbers.

// Create a function using a function
function sum(a,b){
    console.log(a + b);
}

// Call the function
sum(1.2); / / 3
Copy the code

Analysis: can be defined in the () () function of one or more parameters (in the form of parameters, and showed no specific value, just in order to occupy the position), use between parameters, separated, statement parameter is equivalent to the function body, corresponding variable declaration, but there is no assignment, specific assignment depends on the function, the actual argument value.

Note:

  • When calling a function/using a function, you can use the(a)Specifies the arguments (actual parameters) in.
  • When called, it willOne to one correspondenceAssigns a value to the parameter.

Instructions:

  • The function parser is not checked when calledThe argumentsThe type of
  • The parser also does not check when a function is calledThe argumentsThe number of

🚀T- Tests call the function parser without checking the type of the argument.

/ / define
function sum(a, b) {
    console.log(a + b);
}

/ / call
sum(123."hello"); // 123hello
sum(true.false); / / 1
Copy the code

Analysis: Because the parser does not check the type of the argument, it can be combined arbitrarily. The first call is easy to understand. The second 0 + 1 = 1.

🚀T- When a function is called, the parser also does not check the number of arguments.

/ / define
function sum(a, b) {
    console.log(a + b);
}

/ / call
// If the number of arguments passed is less than the number of parameters, the parameter with no corresponding argument is undefined
sum(123); // NaN
// If the number of arguments passed exceeds the number of parameters, the extra arguments are not checked
sum(false.true.1); / / 1
Copy the code

The number of parameters corresponds to the number of arguments. For 123 + B, it is undefined because B does not pass a value, and the result is 123 + undefiend = NaN. Note that number + Undefined = NaN.

(after)

The return value of the function

Concept: The input determines the output of a function, and the return value is the value that needs to be output.

Reason: The execution result of a function needs to be used as an intermediate value for backup or as an input parameter to other functions.

1, function return value demonstration

🚀T- Create a function that computes the sum of three numbers.

function sum(a,b,c){
    alert(a+b+c);
}
sum(1.2.3); / / 6
Copy the code

2. Use of function return values

You can use return as the return value of a function

Format:

{
    / / the function body
    returnValue; }Copy the code

Example:

function sum(a,b,c){
    var d = a + b + c;
    return d;
}
// Call the function
//sum(1,2,3) is returned by the function and assigned to result
var result = sum(1.2.3); 
Copy the code

The value after the return is returned as the result of the function’s execution

Notes and Instructions:

  1. None of the statements following return are executed.
  2. If return is not followed by any value, undefined is returned
  3. Undefined is returned without return
  4. A return can return any type of value, which will be the return value of the entire function

The argument type can be arbitrary

1. Basic type parameters

🚀T- Defines a function that calculates the area of a circle based on the radius and returns the return value.

/ / 3.14 * r * r
function area(r){
    return 3.14*r*r;
}
result = area(2);
console.log("result = " + result); / / result = 12.56
Copy the code

2. Reference type parameters

🚀T- Create a function that prints the person’s information in the console

1) Common way

// Can output name, age,gender,address
function sayHello(name , age, gender , address){
    console.log("I am"+name,"This year"+age+"Age"."Gender"+gender,"Live at home"+address);
}
sayHello("Sun Wukong".18 ,"Male" ,"Flower and Fruit Hill");
Copy the code

Analysis: in this way, if the number of parameters is relatively small, it is good to say, if the number of parameters is more, the order is easy to disorder, modify up trouble.

2) Use an object as a parameter

The improved

function sayHello(o){
    console.log("I am"+o.name,"This year"+o.age+"Age"."Gender"+o.gender,"Live at home"+o.address);
}
// Create an object
var obj = {
    name:"Sun Wukong".age:18.gender:"Male".address:"Flower and Fruit Hill"}; sayHello(obj);// The object is treated as a parameter, indicating that the parameter can be of any type
Copy the code

Note: Using variables to represent values in programming makes the program more flexible.

3. Extension and expansion

// define the summation function sum
function sum(a){
   return a+a;
}
// Define the function fun
function fun(a){
   console.log("a = " + a);
}
// Call fun
fun(sum);
Copy the code

Call fun(sum) result:

a = function sum(a) {
    return a + a;
}
Copy the code

No arguments are passed to the sum function. The sum object is passed, and the effect is to print out the sum object

function sum(a){
   return a*a;
}
function fun(a){
   console.log("a = " + a);
}
fun(sum(6));
Copy the code

Pass the parameter, and the return value is returned

Notice the difference:

  • Function object: sum
  • Return value: sum()

There is a difference between teaching a man to fish and teaching him to fish

4. Execute the function immediately

Concept: Executing a function immediately is using it immediately. The identification of a function object or function name represents the function. The body of the function is the real functional part of the function. The order of function understanding: function function first, after the function name, name, call and make it, the name of call, wait for that. Can I use it once or not? Functions with features like this are also called anonymous functions in other programming languages.

Format:

 ( function() {function body}) ();Copy the code

Example:

(function(){
    console.log("hello"); }) ();Copy the code

Console print result:

hello
Copy the code

(function name, parameter list, function body); (function name, parameter list, function body); The immediate function combines ① and ②. The form is () (), the first () is to wrap the function definition part as a “function name”, the second () is the function call, like the normal way ① define function test(){},② call test(). Note that the function name must be enclosed in parentheses, otherwise an error will be reported.

Q: Why do functions need function names?

A: Actually, the function name is not necessary. The purpose of using A function is to execute the content part of the function, to achieve A certain function, to achieve A certain purpose. Function names are used primarily for aspect “use” functions, which can be called multiple times, from other locations. Thus it can be seen that the function name plays a role in replacing the onerous function body, function itself.

To print the “function name” is to call the function without (), resulting in the function body.

🚀T- The test function object name is the function itself.

function test() {
    console.log("I'm something in the body of a function.");
}

// // // Calls a function with its name
test();

// // // Print test()
console.log("Print test() function:" + test() );
// // // Prints test
console.log("Print test: \n" + test);
Copy the code

Console output:

I'm the contents of the function body. I'm the contents of the function body. Print the test() function:undefinedPrint the test:function test() {
    console.log("I'm something in the body of a function.");
}
Copy the code

Test is called only once, but printed twice. ⭐⭐⭐ When the console.log() function is printed, two processes are actually performed: (1) printing the contents of the function body, and (2) returning the value returned by the function. The test function above returns neither a value nor a return, so the return value is undefined. The two output results refer to test() and console.log(” Print test() function: “+ test()); .

According to the above console.log(” print test: \n” + test); You know that the name test is actually the body of the function (the definition part).

To summarize the essential parts of a function:

1) Definition of function

function   ()         {}; Function declaration parameter list Function function body Function end flagCopy the code

2) Function call

( function () {};) (a); The function itself forms the end flagCopy the code

Function names are created just for convenience, like the name of a person.

(after)