Focus onThe front small Ou, read more original technical articles
- The function isobjectEvery function is
Function
Type, have the same as any other reference typeattributeandmethods - A function name is a pointer to a function object and is not bound to a function (a function may have multiple names).
Related code →
Four ways to define it
Function sum(num1, num2) {return num1 + num2} // 2. Let sum = function (num1, num2) {return num1 + num2} // 4. Let sum = (num1, num2) => {return num1 + num2} // 4. Var sum = new Function('num1', 'num2', 'return num1+num2')
10.1 Arrow functions
- Arrow functions can be used anywhere a function expression can be used
let arrowSum = (a, b) => {
return a + b
}
let functionExpressionSum = function (a, b) {
return a + b
}
console.log(arrowSum(5, 8)) // 13
console.log(functionExpressionSum(5, 8)) // 13
- If you have only one argument, you can leave out parentheses (parentheses are required for multiple arguments or no arguments)
let double = (x) => {
return x * 3
}
console.log(double(3)) // 9
- You can do without braces. If you do, you can only have one line of code after the arrow (assignment or expression) and implicitly return the value of that line (no return).
Let person = {obj} let setName = (obj) => (obj. Name = 'Matt') let setName = (obj) => (obj. Name = 'Matt' Return (obj.name = 'Matt')} setName(person) console.log(person.name) // "Matt"
-
Where the arrow function is not applicable:
- You can’t use
arguments
,super
andnew.target
- Cannot be used as a constructor
- There is no
prototype
Attributes ()
- You can’t use
10.2 the function name
- A function name is a pointer to a function, and a function can have more than one name
function sum(num1, num2) { return num1 + num2 } console.log(sum(10, 10)) // 20 var anotherSum = sum Console. log(anotherSum(10, 10)) // 20 sum = null // console.log(sum(10, 10)) // sum is not a function
- All ES6 function objects expose oneread-onlythe
name
Property, saved by defaultFunction identifier(String function name) - No function nameIs identified as an empty string, using
Function
Constructor creation is identified asanonymous
Function foo() {} // let bar = function () {} // let baz = () => {} // Console.log (foo.name) // 'foo' Console. log(bar.name) // 'bar' console.log(baz. Name) // 'baz' console.log((() => {}).name) // Empty string console.log(new) Function().name) // 'anonymous'
- If the function is an get function, set function, or instantiated using bind(), the identifier is prefixed
Console. log(foo.bind(null).name) // 'bound fooo ', prefix let dog = {years: 1, get age() { return this.years }, set age(newAge) { this.years = newAge }, } let propertyDescriptor = Object.getOwnPropertyDescriptor(dog, Var name = "propertyDescriptor"; var name = "propertyDescriptor"; var name = "propertyDescriptor"; var name = "propertyDescriptor" true, configurable: True} the console. The log (propertyDescriptor. Get. Name) / / 'get the age', Identifier before prefixing the console. The log (propertyDescriptor. Set. Name) / / 'set age, prefixing before identifier
10.3 Understand parameters
- The JS function does not care about the number of arguments and data types passed in
- Can be inNonarrow functionInternal access
arguments
An array of classObject to get each parameter (e.garguments[0]
) - The named parameters of a JS function do not have to match the function signature when called, and there is no mechanism to verify the named parameters
function sayHi(name, message) { console.log(`Hello ${name}, ${message}`) } function sayHi2(name, message) { console.log(`Hello ${arguments[0]}, ${arguments[1]} ')} function sayHi3() {console.log(' Hello ${arguments[0]}, ${arguments[1]} ')} sayHi3('Jake', ${arguments[1]} ')} 'How are you') // 'Hello Jake, How are you' sayHi2('Jake', 'How are you') // 'Hello Jake, How are you' sayHi3('Jake', 'How are you') // 'Hello Jake, How are you'
- Can be achieved by
arguments.length
Check the number of arguments passed in
Function howManyargs () {console.log(arguments.length) // Check the number of arguments} howManyargs (' String ', 45) // 2 howManyArgs() // 0 howManyArgs(12) // 1
arguments
Object can be used with named parameters
function doAdd(num1, num2) { if (arguments.length === 1) { console.log(num1 + 10) } else if (arguments.length === 2) { Console. log(arguments[0] + num2)}} doAdd(10) // 20, 10+10 doAdd(30, 20) // 50,30 +20
-
The values of the Arguments object are always synchronized with the named arguments
- Separate in memory (not access to the same address), only value synchronization
- Arguments not passed when a function is called will not be passed because
arguments
Change and change (always undefined)
function args(num1, num2) { arguments[1] = 10 console.log(num1, num2) } args(2, 3) // 2 10 function args2(num1, Num2) {arguments[1] = 10 console.log(num1, num2)} args2(2) // 2 undefined, only one argument is passed to call function, changing arguments does not change the second named argument, Undefined function args3(num1, num2) {num1 = 10 console.log(arguments[0], arguments[1])} args3(2, 3) // 10 3
-
In strict mode, arguments have some changes:
arguments
Object values and named parametersNo longer sync, modifyarguments
Named parameters are no longer affected- Rewrite it in a function
arguments
The object will report an error and the code will not execute
function strictArgs(num1, num2) { 'use strict' arguments[1] = 10 console.log(num1, num2) // arguments = [] // SyntaxError: Unexpected eval or the arguments in strict mode, can not rewrite the arguments} strictArgs (2, 3) / / 2, 3, and the arguments and named parameters are no longer in sync
- Arrow functionCan not access
arguments
Only named parameters can be accessed
let bar2 = (num1, num2) => {
// console.log(arguments[0], arguments[1]) // Uncaught ReferenceError: arguments is not defined
console.log(num1, num2)
}
bar2(2, 3) // 2 3
- All parameters in JS are passed by value. If an object is passed as a parameter, the value passed is a reference to the object (still passed by value).
10.4 No reloads
- JS functions are not signed, so they are not overloaded. A function with the same name defined later will override the function defined earlier
function addSomeNumber(num) { return num + 100 } function addSomeNumber(num) { return num + 200 } let result = Let addSomeNumber2 = function (num) {return num + 100} addSomeNumber2 = function (num) { return num + 200 } let result2 = addSomeNumber2(100) console.log(result2) // 300
10.5 Default parameter values
- Before ES5, a common way to implement a default parameter is to check whether a parameter is equal to undefined
function makeKing(name) { name = typeof name ! == 'undefined' ? name : 'Henry' // Check if the parameter name is undefined, Return 'King ${name} VIII'} console.log(makking ()) // 'King Henry VIII' console.log(makking ('James')) // 'King James VIII'
- ES6 and later support explicit definition of default parameters, which can be assigned after the parameters in the function definition
function makeKing2(name = 'Henry') {
return `King ${name} VIII`
}
console.log(makeKing2()) // 'King Henry VIII'
console.log(makeKing2('James')) // 'King James VIII'
- When default parameters are used,
arguments
objectDo not reflect parameter defaults, only parameters passed to the function, changing the named parameter does not affectarguments
object
Function makeKing3(name = 'Henry') {name = 'Louis' return 'King ${arguments[0]}'} console.log(makeKing3()) // 'King James', 'King James', 'King James'.
- You can use the return value of the calling function as the default parameter value. The function that evaluates the default value is called without passing the corresponding parameter
Let RomanNumerals = [" Ⅰ ", "eh", "eh", "eh", "eh", "Ⅵ"] let ordinality = 0 function getNumerals() {return RomanNumerals [ordinality++] // function makeKing4(Name = 'Henry', numerals = getNumerals()) {return 'King ${name} ${numerals} '} console.log(makeKing4()) // "King Henry Ⅰ" The function getNumerals() console.log(makeKing4(" James ", "Ⅸ")) // "King James" was called, and the parameters of Numerals were passed. // "King Henry Ⅱ" without calling the function console.log(MakeKING4 ()) The calling function GetNumerals () console.log(makeKing4()) // "King Henry Ⅲ" without passing the numerals parameter, the calling function GetNumerals ()
- Arrow functions can also take default arguments. You cannot omit parentheses if you have only one argument
let makeKing5 = (name = 'Henry') => `King ${name}`
console.log(makeKing5()) // 'King Henry'
Default parameter scope and temporary dead zone
- Default values for parameters are, in effect, used
let
The keywordAccording to the orderThe same as declaring variables
function makeKing6(name = 'Henry', Numerals = 'Ⅷ') {return 'King ${name} ${numerals}'} '} // function makeKING7 () {let name = 'Henry' let Numerals = 'Ⅷ' return 'King ${name} ${numerals}'}
- Default values are then definedThe parameter ofReferences the parameters defined previously; And the other way around becauseTemporary dead zoneAn error (
let
Declared variableWill not be promoted in scope)
function makeKing8(name = 'Henry', numerals = name) { return `King ${name} ${numerals}` } console.log(makeKing8()) // 'King Henry Henry' function makeKing9(name = numerals, Numerals = 'Ⅷ') {return 'King ${name} ${numerals}'} // console.log(makeKing9()) // ReferenceError: Cannot access 'numerals' before initialization
- A parameter has its own scope and cannot refer to the scope of the function body
function makeKing10(name = 'Henry', numerals = defaultNumeral) {
let defaultNumeral = 'Ⅷ'
return `King ${name} ${numerals}`
}
// console.log(makeKing10()) // ReferenceError: defaultNumeral is not defined
10.6 Parameter expansion and collection
- New extension operators in ES6… Can be used to pass arguments and define function parameters when calling a function
10.6.1 Extension parameters
- You can apply an extension operator to an iterable object and pass it in as a parameter, splitting the iterable object and passing in each value returned by the iteration
let values = [1, 2, 3, 4] function getSum() { let sum = 0 for (let i = 0; i < arguments.length; i++) { sum += arguments[i] } return sum } console.log(getSum(... Values)) // 10 1+2+3+4
- Additional values can be passed before and after the extension operator
console.log(getSum(-1, ... Values)) // 9, -1+1+2+3+4 console.log(getSum(... Values, 5)) / / 15, 1 + 2 + 3 + 4 + 5 console. The log (getSum (1,... Values, 5)) / / 14, 1 + 1 + 2 + 3 + 4 + 5 console. The log (getSum (... values, ... [5, 6, 7]) // 28,1 +2+3+4+5+6+7
arguments
The object still receives each value as the argument passed in when the function is called
function countArgs() { console.log(arguments.length) } countArgs(-1, ... values) // 5 countArgs(... values, 5) // 5 countArgs(-1, ... values, 5) // 6 countArgs(... values, ... [5, 6, 7]) // 7
- Default parameters can be used as well as the extension operator
function getProduct(a, b, c = 1) { return a * b * c } console.log(getProduct(... [1, 2])) // 2* 2*1 console.log(getProduct(... [1, 2, 3]) // 1*2*3 console.log(getProduct(... Let getSum2 = (a, b, c = 0) => {return a + b + c} console.log(getSum2(... [0, 1])) // 1, 0+1 console.log(getSum2(... [0, 1, 2]) // 3,0 +1+2 console.log(getSum2(... [0, 1, 2, 3]) // 3 0+1+2
10.6.2 Collect parameters
- You can use the extension operator to combine independent arguments of different lengths into an array
function getSum3(... values) { return values.reduce((pre, cur) => pre + cur, 0) } console.log(getSum3(1, 2, 3)) // 6
- Because the result of the collected parameter is variable, it should only be used as the last parameter
- If there are named parameters before the collection parameter, only the remaining parameters are collected. If it is not collected, an empty array is obtained
function getProduct(... values, lastValue) {} // SyntaxError: Rest parameter must be last formal parameter function ignoreFirst(firstValue, ... Values) {console.log(values)} ignoreFirst() // [], ignoreFirst(1) // [], ignoreFirst(1, 2) // [2], ignoreFirst(1, 2) IgnoreFirst (1, 2, 3) // [2, 3
- Arrow functionsupportThe manner in which the collection parameters are defined, implemented and used
arguments
Same logic
let getSum4 = (... values) => values.reduce((pre, cur) => pre + cur, 0) console.log(getSum4(1, 2, 3, 4)) // 10
- Collect parametersDoes not affect the
arguments
Object that still reflects the arguments passed to the function when called
function getSum5(... values) { console.log(arguments.length) // 4 console.log(arguments) // [Arguments] { '0': 1, '1': 2, '2': 3, '3': 4 } console.log(values) // [ 1, 2, 3, 4 ] } getSum5(1, 2, 3, 4)
10.7 Function declarations and function expressions
- Before the JS engine executes the code, the parser uses a process of function declaration hoisting to place the declared function at the top of the source tree and make it available (accessible) before any code is executed. Function expressions, on the other hand, must wait until the parser reaches the line of code before being interpreted.
- The only difference between a function declaration and a function expression is when can a function be accessed through a variable
Console. log(sumDeclare(10, 10)) // function sumDeclare(num1, num1) Num2) {return num1 + num2} console.log(SumExpression (10, 10))) // The function expression does not advance and returns an error, sumExpression is not a function let sumExpression = function (num1, num2) { return num1 + num2 }
10.8 Functions as values
- Function names are variables in ECMAScript. A function can be used as an argument to another function or can return another function within a function
- If you are accessing a function pointer rather than calling a function, you must leave parentheses alone
function callSomeFunction(someFunction, someArgument) { return someFunction(someArgument) } function add10(num) { return num + 10 } let result3 = CallSomeFunction (add10, 10) // To access a pointer to the function instead of executing it, Console. log(result3) // 20 function getGreeting(name) {return 'Hello,' + name // Hello,Nicholas} let result4 = callSomeFunction(getGreeting, 'Nicholas') // Access the pointer to the function instead of execution, getGreeting without parentheses console.log(result4) // 'Hello,Nicholas'
- Sorting by an object attribute of an array object: Define a function that creates a comparison function based on the attribute name
function arraySort(key, sort) { return function (a, (b) {if sort = = = 'asc' | | sort = = = undefined | | sort = = = ' ') {/ / positive sequence: a[key] > b[key] if (a[key] > b[key]) return 1 else if (a[key] < b[key]) return -1 else return 0 } else if (sort === 'desc') {// reverse order: a[key] < b[key] if (a[key] < b[key]) return 1 else if (a[key] > b[key]) return -1 else return 0 } } } var userList = [ { name: 'Tony', id: 3 }, { name: 'Tom', id: 2 }, { name: 'Jack', id: 5 }, ] console.log(userList.sort(arraySort('id'))) // [{ name: 'Tom', id: 2 },{ name: 'Tony', id: 3 },{ name: Sort(arraySort('id', 'desc')))) // [{name: 'Jack', id: 5},{name: 'Tony', id: 3},{name: 'Tom', id: 2}], console.log(userList.sort(arraySort('name'))) // [{name: 'Jack', id: 5},{name: 'Tom', id: 2},{name: 'Tony', id: 3}], in order of name
Summary & Questions
- What is the function? How many ways can a function be defined?
- When can arrow functions do without parentheses for arguments? When can I not use curly braces around the body of a function?
- Why can’t arrow functions be used as constructors or to define prototype methods?
- What is the name of the function? How many function names can a function have? How do I get a function identifier?
- What is the arguments object inside the function? What are the characteristics and limitations of its use?
- How to understand and prove that JS functions are not overloaded?
- How to define the default parameters of a function before and after ES5, ES6 and ES6?
- What does the arguments object have to do with the function default argument? How do you understand the scope and temporary dead zone of default parameters?
- What does the extension operator do? What effect does using arguments when defining arguments have on arguments?
- How do arrow functions implement the same logic as arguments to get each argument?
- What is the difference between function declarations and function expressions?
- Write a piece of code to sort by one of the object properties in the object array. The sorting properties and ascending/descending order can be determined by the parameters