The default parameters

Solve a problem:

  1. Mandatory items are not filled in wrong

  2. Some parameters are given default values when no parameters are passed

Before ES6, you cannot specify default values for function parameters. ES6 allows you to set default values for function parameters, that is, directly after the parameter definition

//es5   
function ajax(url,method,dataType) {
    if(typeof url === 'undefined') throw Error('URL cannot be empty'); method=method? method:'GET';
}

//es6
function ajax(url=Error('URL cannot be empty'),method='GET',dataType='json') {
    console.log(url);
    console.log(method);
    console.log(dataType);
}
ajax('/user')
/*
/user
GET
json
*/
// The above script compiles to es5
function ajax() {
  var url = arguments.length > 0 && arguments[0]! = =undefined ? arguments[0] : Error('URL cannot be empty');
  var method = arguments.length > 1 && arguments[1]! = =undefined ? arguments[1] : 'GET';
  var dataType = arguments.length > 2 && arguments[2]! = =undefined ? arguments[2] : 'json';
  console.log(url);
  console.log(method);
  console.log(dataType);
}
Copy the code

Parameter variables are declared by default, so they cannot be declared again with let or const

In the following code, the parameter variable x is declared by default. It cannot be declared again in the function body using let or const, otherwise an error will be reported.

function foo(x = 5) {
  let x = 1; / / an error
  const x = 2; / / an error
}
Copy the code

2. When using the parameter default values, the functionCannot have arguments with the same name

/ / is not an error
function foo(x, x, y) {
  // ...
}

/ / an error
function foo(x, x, y = 1) {
  // ...
}
Copy the code

3. The default value of a parameter is not passed, but is recalculated each time

let x = 99;
function foo(p = x + 1) {
  console.log(p);
}

foo() / / 100

x = 100;
foo() / / 101
Copy the code

Use of deconstruction assignment

Basic version: No transmission will report an error

function foo({x, y = 5}) {
  console.log(x, y);
}

foo({}) // undefined 5
foo({x: 1}) / / 1 5
foo({x: 1.y: 2}) / / 1. 2
foo() TypeError: Cannot read property 'x' of undefined
Copy the code

Full version: do not pass nor error

function foo({x, y = 5} = {}) {
  console.log(x, y);
}

foo() // undefined 5
Copy the code

Two ways of writing the full version :(usually using notation 1)

The default value of the first function argument is empty object, but sets the default value of object destruct assignment.

The default value of the two function arguments is an object with specific properties, but the default value of the object’s destruct assignment is not set.

/ / write one
function m1({x = 0, y = 0} = {}) {
  return [x, y];
}

/ / write two
function m2({x, y} = { x: 0, y: 0 }) {
  return [x, y];
}

// The function has no arguments
m1() / / [0, 0]
m2() / / [0, 0]

// both x and y have values
m1({x: 3.y: 8}) / / [3, 8]
m2({x: 3.y: 8}) / / [3, 8]

// if x has a value and y has no value
m1({x: 3}) / / [3, 0]
m2({x: 3}) // [3, undefined]

// if x and y have no values
m1({}) / / (0, 0),
m2({}) // [undefined, undefined]

m1({z: 3}) / / [0, 0]
m2({z: 3}) // [undefined, undefined]
Copy the code

Set the default value for non-trailing arguments, which cannot be omitted

Arguments with default values are not tail arguments. In this case, you cannot omit this parameter without the following parameter, unless you explicitly type undefined at the corresponding position of the parameter you do not want to pass (null does not work).

Parameter corresponding to undefined will trigger the default value, null will not trigger the default value

/ / a
function f(x = 1, y) {
  return [x, y];
}

f() // [1, undefined]
f(2) // [2, undefined])
f(, 1) / / an error
f(undefined.1) / / [1, 1)

/ / two cases
function f(x, y = 5, z) {
  return [x, y, z];
}

f() // [undefined, 5, undefined]
f(1) // [1, 5, undefined]
f(1.2) / / an error
f(1.undefined.2) / / [1, 5, 2)
Copy the code
function foo(x = 5, y = 6) {
  console.log(x, y);
}

foo(undefined.null)
// 5 null
Copy the code

Residual operator application

//arguments uses residual operators
function fn(context,... arg){
    // Get the first and the rest of the passed values
    console.log(context)
    console.log(arg)   // Arg is an array and arguments is an array of classes

}
var obj={name:'aaa'}
fn(obj,10.20)
Copy the code

Expand operator application

let arr=[12.23.34];
let fn=function(a,b,c){
    console.log(a,b,c)
}
//fn(arr) //arr undefined undefinedfn(... arr)//=>fn(12,23,34) => Print 12,23,34
Copy the code

Arrow function

Arguments (); And arg is an array

Arrow functions have no execution body, just no this

2. In the arrow function, this is fixed and will not change

3. The this object inside a function is the object at which it is defined, not used

4. Use this in arrow functions directly from the context of this (this in parent scope, not parent code block {}, or parent JSON object)

This in arrow functions does not matter if it is preceded by a dot, because it does not have an execution body. This in arrow functions is used directly from the context of this (this in parent scope, not parent code block {} or parent JSON object).

5. Do not use it as a constructor, that is, do not use the new command, otherwise an error will be thrown

6. Arrow functions cannot be used as Generator functions because yield cannot be used

let fn=(x,y) = >{

}
fn(10.20)
Copy the code

7. Only one parameter can omit the parentheses

let fn= x= >{

}
fn(10)
Copy the code

8. If there is only one operation in the function body and it is return, we can omit the braces and return

Arrow functions that have more than one statement in the code block enclose them in braces and return with a return statement.

let fn= function(x,y){
	return x+y;
}
fn(10.20)

let fn=(x,y) = >x+y;
console.log(fn(10.20))  / / 30

let fn=(x=0,y=0) = >x+y;    // Set default values for the parameters
console.log(fn(10.20))  / / 30
Copy the code
let fn= x= > y= > x+y
/* = let fn= x =>(y => x+y) */
let fn=function(x){
	return function(y){
		returnx+y; }}Copy the code
let fn =(. arg) = >{
	//arg is all arguments, and arg is an array
}
fn(10.20.30)
Copy the code

9. If the arrow function returns an object directly, it must enclose parentheses around the object, otherwise an error will be reported.

/ / an error
let getTempItem = id= > { id: id, name: "Temp" };

/ / is not an error
let getTempItem = id= > ({ id: id, name: "Temp" });
Copy the code
// This in arrow functions is used directly from the context of this (this in parent scope, not parent code block {}, or not parent JSON object)
let obj={
    name:'aaa'.fn:() = >{
        console.log(this.name)
    }
}
let obj2={
    name:'bbb'.fn:obj.fn
}
obj.fn();       //undefined
obj2.fn();      //undefined
Copy the code

sample

Example 1: change obj. Fn’s this to window

let obj={
	fn: (function(){
		/ / this: window
		return function(){
			console.log(this)
		}
	})()
}
obj.fn();      //this:obj

/ / 1.
obj.fn.call(window)


/ / 2,
let obj={
	fn: (function(){
		/ / this: window
		var _this=this;
		return function(){
			console.log(_this)
		}
	})()
}

/ / 3.
let obj={
	fn: (function(){
		/ / this: window
		return () = >{
			/ / this: window
			console.log(this)
		}
	})()
}
obj.fn();      //this:window

Copy the code

Case 2,

This is the window in this function

let obj={
    name:'aaa'.fn:function(){
        var self=this;
        console.log(this.name);
        console.log(self.name);
        ~function() {
            console.log(this.name)
            console.log(self.name)
        }()
    }
}
obj.fn()  


//aaa
//aaa
//undefined
//aaa
Copy the code

This in the arrow function is the this of the scope in which it is defined

let obj={
    name:'aaa'.fn:function(){
        var self=this;
        console.log(this.name);
        console.log(self.name);
        (() = > {
            console.log(this.name)
            console.log(self.name)
        })()
    }
}
obj.fn()

//aaa
//aaa
//aaa
//aaa
Copy the code

This = window; this = window; This in the arrow function is defined in the scope of this, let is not defined in the window

let name='global';
let obj={
    name:'aaa'.fn: (function(){
        var self=this;
        console.log(this.name);
        console.log(self.name);
        return () = > {
            console.log(this.name)
            console.log(self.name)
        }
    })()
}
obj.fn()
//undefined
//undefined
//undefined
//undefined
Copy the code

This = window; this = window; This in the arrow function is the this of the scope in which it is defined

let obj={
    name:'aaa'.fn: (function(){
        var self=this;
        console.log(this.name);
        console.log(self.name);
        return function(){
            console.log(this.name)
            console.log(self.name)
        }
    })()
}
obj.fn()

//undefined
//undefined
//aaa
//undefined
Copy the code

Arrow functions cannot be used in the following cases:

1. Define a method of the function that includes this inside

const cat = {
  lives: 9.jumps: () = > {
    this.lives--; }}Copy the code

2. Arrow functions should also not be used when dynamic this is required