当前位置:网站首页>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
边栏推荐
- CANN训练营学习2022第二季 模型系列 动漫风格化和AOE ATC调优
- Interview question 01.02. determine whether it is character rearrangement
- [array]nc143 matrix multiplication - simple
- It's time to consider slimming down your app
- The industrial information security center takes the lead in building a data circulation platform, and ant group and other manufacturers provide technical support
- An example of using viewthatfits adaptive view in swiftui 4.0
- Navicate connects Alibaba cloud (explanation of two methods and principles)
- Comparison of array and object merging methods assign, merge, defaults, defaultsdeep in lodash
- quick get start
- MySQL addition, deletion, modification, retrieval and constraint (detailed teaching)
猜你喜欢

通道的分离与合并
![[GNN report] Tencent AI Lab Xu TingYang: graph generation model and its application in molecular generation](/img/5f/c790baf8f8e62fca36fdb4492c38b2.png)
[GNN report] Tencent AI Lab Xu TingYang: graph generation model and its application in molecular generation

Implementation of side list menu (side menu) of wechat applet

Live review | wonderful playback of Apache pulsar meetup (including PPT download)

One article of quantitative framework backtrader: understand indicator indicators

Number theory division block explanation example: 2021 Shaanxi Race C

Xxx.pro learning in QT

JVM class loading subsystem

调整图像亮度的滚动条演示实验

CDN (content delivery network) content distribution network from entry to practice
随机推荐
内核开发
MySQL addition, deletion, modification, retrieval and constraint (detailed teaching)
Is it safe for Mr. qiniu to open a securities account? Can I drive it?
UFW port forwarding
SS-Paper【1】:Fully Convolutional Networks for Semantic Segmentation
Atcoder beginer 202 e - count descendants (heuristic merge on heavy chain split tree for offline query)
opencv自带颜色操作
Coldplay weekly issue 10
2022-07-21 Daily: Wu Enda wrote: how to establish projects suitable for AI career
键盘输入操作
Programming language exercises (I)
Reptiles and counter crawls: an endless battle
Yolopose practice: one-stage human posture estimation with hands + code interpretation
ShardingSphere数据库读写分离
Comparison of array and object merging methods assign, merge, defaults, defaultsdeep in lodash
Internet Download Manager Configuration
ShardingSphere数据库读写分离
AXI协议(3):AXI架构的握手机制和实现细节
Small end format and big end format (little endian & big endian)
Iftnews | Christie's launched its venture capital department, aiming at Web3 and metauniverse industries