当前位置:网站首页>Extension of ES6 function
Extension of ES6 function
2022-07-24 17:19:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm your friend, Quan Jun .
- The default value of the function parameter
- Used in conjunction with deconstruction assignment defaults
- rest Parameters
- Strict mode
- name attribute
- Arrow function
- Nested arrow functions
- Comma at the end of a function argument
The default value of the function parameter
ES6 Before , You can't directly specify default values for parameters of a function , We can only take a flexible approach .
function log(x, y) {
// y = y || 'World';
if (typeof y === 'undefined') {
y = 'World';
}
console.log(x, y);
}
log('Hello') // Hello World
log('Hello', 'China') // Hello China
log('Hello', '') // Hello WorldES6 Allows you to set default values for parameters of a function , That is, it is written directly after the parameter definition .
function log(x, y = 'World') {
console.log(x, y);
}
log('Hello') // Hello World
log('Hello', 'China') // Hello China
log('Hello', '') // Hello Parameter variables are declared by default , So it can't be used let or const Once again .
function foo(x = 5) {
let x = 1; // error
const x = 2; // error
}Used in conjunction with deconstruction assignment defaults
function foo({x, y = 5} = {}) {
console.log(x, y);
}
foo() // undefined 5function fetch(url, { body = '', method = 'GET', headers = {} } = {}) {
console.log(method);
}
fetch('http://example.com')
// "GET"rest Parameters
ES6 introduce rest Parameters ( In the form of … Variable name ), Extra arguments to get functions , So you don't need to use arguments Object .rest The argument is an array , This variable puts extra parameters in the array .
function add(...values) {
let sum = 0;
for (var val of values) {
sum += val;
}
return sum;
}
add(2, 5, 3) // 10Be careful ,rest Parameters cannot be followed by any other parameters ( It can only be the last parameter ), Otherwise, an error will be reported .
// Report errors
function f(a, ...b, c) {
// ...
}Strict mode
ES2016 Made a little modification , Specifies that as long as a function parameter uses a default value 、 Deconstruct assignment 、 Or extension operators , Then the function interior cannot be explicitly set to strict mode , Otherwise, an error will be reported .
// Report errors
function doSomething(a, b = a) {
'use strict';
// code
}
// Report errors
const doSomething = function ({a, b}) {
'use strict';
// code
};
// Report errors
const doSomething = (...a) => {
'use strict';
// code
};
const obj = {
// Report errors
doSomething({a, b}) {
'use strict';
// code
}
};name attribute
Functional name attribute , Returns the function name of the function .
function foo() {}
foo.name // "foo"This property has long been widely supported by browsers , But until ES6, Before it was written into the standard .
It should be noted that ,ES6 Some modifications have been made to the behavior of this property . If you assign an anonymous function to a variable ,ES5 Of name attribute , Will return an empty string , and ES6 Of name Property returns the actual function name .
var f = function () {};
// ES5
f.name // ""
// ES6
f.name // "f"If you assign a named function to a variable , be ES5 and ES6 Of name Property returns the original name of the named function .
const bar = function baz() {};
// ES5
bar.name // "baz"
// ES6
bar.name // "baz"Arrow function
ES6 Allow to use “ arrow ”(=>) Defined function .
var f = v => v;
// Equate to
var f = function (v) {
return v;
};If the arrow function does not require parameters or requires more than one parameter , Just use a parenthesis to represent the parameter part .
var f = () => 5;
// Equate to
var f = function () { return 5 };
var sum = (num1, num2) => num1 + num2;
// Equate to
var sum = function(num1, num2) {
return num1 + num2;
};If the code block part of the arrow function is more than one statement , Just use curly braces around them , And use return Statement returns .
var sum = (num1, num2) => { return num1 + num2; }Because braces are interpreted as code blocks , So if the arrow function returns an object directly , You have to put parentheses around the object , Otherwise, an error will be reported .
// Report errors
let getTempItem = id => { id: id, name: "Temp" };
// Don't complain
let getTempItem = id => ({ id: id, name: "Temp" });Arrow function can be used in combination with variable deconstruction .
const full = ({ first, last }) => first + ' ' + last;
// Equate to
function full(person) {
return person.first + ' ' + person.last;
}One use of the arrow function is to simplify the callback function .
// Normal function writing
[1,2,3].map(function (x) {
return x * x;
});
// Arrow function writing
[1,2,3].map(x => x * x);Here is rest An example of the combination of parameters and arrow functions .
const numbers = (...nums) => nums;
numbers(1, 2, 3, 4, 5)
// [1,2,3,4,5]
const headAndTail = (head, ...tail) => [head, tail];
headAndTail(1, 2, 3, 4, 5)
// [1,[2,3,4,5]]Nested arrow functions
Inside the arrow function , You can also use the arrow function . Here's a ES5 Multiple nested functions of Syntax .
function insert(value) {
return {into: function (array) {
return {after: function (afterValue) {
array.splice(array.indexOf(afterValue) + 1, 0, value);
return array;
}};
}};
}
insert(2).into([1, 3]).after(1); //[1, 2, 3]The function above , You can use the arrow function to rewrite .
let insert = (value) => ({into: (array) => ({after: (afterValue) => {
array.splice(array.indexOf(afterValue) + 1, 0, value);
return array;
}})});
insert(2).into([1, 3]).after(1); //[1, 2, 3]Comma at the end of a function argument
before , When defining and calling functions , Comma after the last parameter is not allowed .
function clownsEverywhere(
param1,
param2
) { /* ... */ }
clownsEverywhere(
'foo',
'bar'
);If it's like this , Write parameters as multiple lines ( That is, each parameter occupies one line ), When modifying the code later , Want to be a function clownsEverywhere Add the third parameter , Or adjust the order of parameters , It is necessary to add a comma after the original last parameter . For the version management system , It will show that the line with comma has also changed . It looks a little redundant , So the new syntax allows you to define and call , There is a comma directly at the end .
function clownsEverywhere(
param1,
param2,
) { /* ... */ }
clownsEverywhere(
'foo',
'bar',
);Such regulations also make , Function parameters and the trailing comma rule of arrays and objects , It's consistent .
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/107446.html Link to the original text :https://javaforall.cn
边栏推荐
- 小端格式和大端格式(Little-Endian&Big-Endian)
- Work with growingio engineers this time | startdt Hackathon
- HCNP Routing&Switching之DHCP中继
- Axi protocol (2): five channels and two transactions of Axi architecture
- Interview question 01.02. determine whether it is character rearrangement
- Iftnews | Christie's launched its venture capital department, aiming at Web3 and metauniverse industries
- Still developing games with unity? Then you're out. Try unity to build an answer system
- Mysql增删改查、检索与约束(详细教学)
- Is it safe for Mr. qiniu to open a securities account? Can I drive it?
- Axi protocol (3): handshake mechanism and implementation details of Axi architecture
猜你喜欢

2022年最新浙江建筑安全员模拟题库及答案

NC port forwarding

Exception handling - a small case that takes you to solve NullPointerException

One article of quantitative framework backtrader: understand indicator indicators

Portmap port forwarding

JSP custom tag library --foreach

Opencv has its own color operation

【时序逻辑电路】——计数器

启发式合并(含一般式、树上启发式合并 例题)

Qsqldatabase: solution of qmmysql driver not loaded
随机推荐
[matlab]: basic knowledge learning
Implementation of side list menu (side menu) of wechat applet
[redis] -1. two ways of setting up environment based on docker
还在用Xshell?你out了,推荐一个更现代的终端连接工具!
Cann training camp learns the animation stylization and AOE ATC tuning of the second season of 2022 model series
AutoCAD - join merge command
Transformer structure analysis -- learning notes
Scroll bar adjust brightness and contrast
1309. Decode letter to integer mapping
TCP协议调试工具TcpEngine V1.3.0使用教程
What is fuzzy theory, foundation and process
Analyze the capabilities and scenarios of Apache pulsar, a cloud native message flow system
Live review | wonderful playback of Apache pulsar meetup (including PPT download)
Shardingsphere database read / write separation
PAT甲级——A + B 格式
Safety: how to provide more protection for pedestrians
Still developing games with unity? Then you're out. Try unity to build an answer system
Work with growingio engineers this time | startdt Hackathon
NC port forwarding
Axi protocol (1): introduction to AMBA bus, introduction to Axi concept and background, characteristics and functions of Axi protocol