Function Parameter Extensions
Default Parameters
Basic Usage
Note: When using function default parameters, duplicate parameter names are not allowed.
Default parameters are used only when no argument is passed, or when the argument is undefined. The null value is considered a valid value passed.
Function parameter default values have a temporal dead zone. In a function parameter default value expression, a parameter value that has not yet been initialized cannot be used as the default value for other parameters.
Rest Parameters
Rest parameters are used to represent an indefinite number of parameters, in the form ...variableName, consisting of ... plus a named parameter identifier. The named parameter can only be placed at the end of the parameter list, and there can be only one rest parameter.
Basic Usage
Arrow Functions
Arrow functions provide a more concise way to write functions. The basic syntax is:
Parameter => function body
Basic usage:
When the arrow function has no parameters or has multiple parameters, use()parentheses to enclose them.
When the arrow function body has multiple statements, use{}curly braces to wrap it, representing a code block. When there is only one statement and a result needs to be returned, you can omit{}, and the result will be returned automatically.
When an arrow function needs to return an object, in order to distinguish it from a code block, use()parentheses to wrap the object.
Note: There are no bindings for this, super, arguments, and new.target.
The this object in the arrow function body is the object at the time the function is defined, not the object at the time the function is used.
It cannot be used as a constructor, meaning you cannot use the new command, otherwise an error will be thrown.
Suitable Use Cases
Before ES6, the this object in JavaScript was always a headache. In callback functions, you often saw code like var self = this, in order to pass the external this into the callback function. With arrow functions, this is no longer needed; you can just use this directly.
Therefore, when we need to maintain a this context, we can use arrow functions.
Unsuitable Use Cases
Defining a function method, and the method contains this
When dynamic this is needed
The listener function of button is an arrow function, so the this inside the listener function points to the outer this object at the time of definition, namely Window, resulting in the inability to operate on the clicked button object.