Extension of a function

Used in conjunction with destructively assigned default values

When a function argument is an object, the argument must also pass an object to use the default value

Ex. :
funtion foo({x,y=5}){
    console.log(x,y);
}
foo({}) //undefined 5
foo() //TypeError
Copy the code

You can do this by using an empty object as the default value for the function’s argument object

Ex. :
functionfoo({x,y=5} = {}){ console.log(x,y); } foo(); //undefined 5Copy the code

If the default value is a concrete object, the argument cannot be empty

function m1({x=0,y=0} ={}){
    return [x,y];
}
function m2({x,y} = {x:0,y:0}){
    return[x,y]; } console.log(m1()); / / [0, 0] the console log (m2 ({})); //[ undefined,undefined]Copy the code

At this point, you need to pass an object in order to destruct the assignment and generate variables x and y

The position of the default value

An argument that defines the default value, usually the last argument to a function. This results in the previous parameters not being defaulted. If you want to use the default values in the previous arguments, you need to fill the position with undefined.

Function length property

The length attribute of the function returns the number of arguments without a default value. The first argument with a default value is not counted.

scope

The parameter actually executes a let, and you need to be aware of the temporary dead zone problem. The argument is a function and you have to pay attention to that as well

A temporary dead zone for the let command

The difference with var is that: 1. Only the declared block is valid. 2. Variable promotion does not exist, so it must be declared before use. When you enter the current scope, the variable already exists, but you must wait for the declaration statement to appear before you can get it and use it.

Rest parameters

Arrow function

Case 1:

var f = v => v;

The first v is the argument, and the second is the return value

Use multiple parameters or no parameters (); If there is one more statement in the code block, use braces to enclose the return statement. Void doesNotReturn() if there is no return value and only one line;

The this object in this function is the object at which it was defined, that is, it is fixed.

function

Declaration of functions

1.Function *name*(* parameter *){}

2.Var *name*=function * Optional _name*(* parameter *){};Variable assignment. Optional name can only be used inside functions.

3.var *name*=Function();

Ex. :

var add= new Function(
    'x'.'y'.'return x+y'
);
Copy the code

Only the last one is used as the body of the function, the others are arguments

4. The function is declared multiple times, depending on the last time, because the function declaration improves.

A function is a value

A function is treated as a value and thus has the same status as (numeric value, string), etc. Where we can use values, we can use functions.

Function declarations, like variable declarations, are promoted to the header of the code.

The attribute method of a function

Name returns the name of the function

For a named function defined using variable assignment, the name is returned, but cannot be used outside the function.

ToString ()f returns a string containing the source code for the function

The scope in which a function executes is defined, not invoked.

Ex. :

var a = 1;
var x = function () {
  console.log(a);
};
function f() {
  var a = 2;
  x();
}
f() // 1
Copy the code

Function x does not refer to internal variables of function f

delivery

If the parameter type is primitive (numeric, string, Boolean), it is passed by value. If it is a compound type, it is

Reference to pass

A function closure

Only the subfunctions inside the function can read the internal variables, and closures allow the internal function to remember the result of the last call. Closures also serve to encapsulate the private properties and methods of an object. Overusing closures has performance issues.

To be continued: arrow function

Asynchronous operations

The main thread is executed only when the prerequisite event completes; Incomplete is in the task queue

Task queues and event loops

The main thread executes all synchronization tasks first. After all synchronization tasks are completed, the system checks whether there are asynchronous tasks that meet the requirements in the task queue. If yes, the system enters the main thread again.

Mode of asynchronous operation

1. Callback function: write f2 as the callback function of f1. Ensure that f1 is executed before F2 is executed

function f1(callback){
    console.log("f1");
    callback();
}
function f2(){
    console.log("f2");
}
f1(f2);
Copy the code

2. Event monitoring: The execution of asynchronous tasks depends on whether an event occurs

3. Serial execution

Var items = [6]; var results = [];function async(arg,callback){
    console.log('Parameter is'+arg+', return result in 1 second ');
    setTimeout(function() {callback(arg*2); }, 1000); }function final(value){
    console.log('Done:',value);
}
function series(item){
    if(item){
        async(item,function(result){
            results.push(result);
            return series(items.shift());
        });
    }else{
        return final(results[results.length-1]);
    }
}
series(items.shift());
Copy the code

4. Parallel execution

Var items = [6]; var results = [];function async(arg,callback){
    console.log('Parameter is'+arg+', return result in 1 second ');
    setTimeout(function() {callback(arg*2); }, 1000); }function final(value){
    console.log('Done:',value);
}
items.forEach(function(item){
    async(item,function(result){
        results.push(result);
        if(results.length === items.length){ final(results[results.length-1]); }})})Copy the code

5. Serial combination

The timer

SetTimeout () and setInterval() are used to add scheduled tasks to the task queue

setTimeout()

1. Specify the number of milliseconds after a function or code segment is executed, returning the number of the period as an integer
2.var timeId = setTimeout(func|code,delay); The second argument elision defaults to 0. Additional arguments are allowed that will be passed to the callback function
3. If the callback function is a method of an object, setTimeout causes the this keyword inside the method to point to the global environment, not to the object at which it was defined. You can use this method to bind to OBj.

setInterval()

This is the same as setTimeout, except that setInterval specifies that a task is executed at intervals.
The interval includes execution time. If you need a fixed interval between two executions, you can specify it using setTimeout
var i = 1;
var timer = setTimeout(function f() {/ /... timer =setTimeout(f, 2000);
}, 2000);
Copy the code

The callback specified by setTimeout setInterval is not executed until the synchronization function is complete, so it may not execute at a predetermined time.

Promise object

meaning

1.Promise is an object from which you can obtain the asynchronous operation’s state, which is pending, which is a pity, which is failed.

2. The state of the Promise is determined only by the asynchronous operation and cannot be modified or terminated

Promise constructor

var promise = new Promise(function (resolve, reject) {
  // ...

  ifResolve (value); }else{/* Async fails */ reject(new Error()); }});Copy the code

Resolve changes its state from “incomplete” to “successful,” while Reject is failed.

Then method

Use to add a callback function

var p1 = new Promise(function(resolve,reject){
    resolve('success');
});
p1.then(console.log,console.error);
Copy the code

1. The then method can accept two callback functions, the first a successful callback and the second a failed one.

2. The THEN method can be chained because it returns a new Proise instance

3.Promise’s callback function is an asynchronous task that will be executed after the synchronous task

new Promise(function(resolve,reject){
    resolve(1);
}).then(console.log);
console.log(2);
Copy the code

Note that the Promise callbacks are actually micro-tasks that are appended to the current event loop, not the normal tasks to the next round.

all()

The promise.all () method is used to wrap multiple Promise instances into a new Promise instance.const p = Promise.all([p1,p2,p3]);

The state of P is determined by (Promise instances) P1, P2, and P3, divided into two cases. (1) Only when the states of P1, P2 and P3 become depressing, the state of P will become depressing. At this time, the return values of P1, P2 and P3 will form an array and be passed to the callback function of P. (2) As long as p1, P2 and P3 are rejected, P becomes rejected, and the return value of the first rejected instance is passed to p’s callback function.