Home > Web Front-end > Front-end Q&A > Example code of ES6 arrow function practice

Example code of ES6 arrow function practice

WBOY
Release: 2022-08-08 10:26:02
forward
992 people have browsed it

This article brings you relevant knowledge about javascript, which mainly introduces issues related to the application of arrow functions. Arrow function expressions are more suitable for places where anonymous functions are originally needed, and It cannot be used as a constructor. Let's take a look at it. I hope it will be helpful to everyone.

Example code of ES6 arrow function practice

[Related recommendations: javascript video tutorial, web front-end

Introduction

The syntax of arrow function expressions is more concise than function expressions, and does not have its own this, arguments, super or new.target. Arrow function expressions are more suitable where an anonymous function would otherwise be required, and it cannot be used as a constructor. ---- MDN

Basic usage

Parameter representation

(param1, param2, …, paramN) => { statements }
(param1, param2, …, paramN) => expression
//相当于:(param1, param2, …, paramN) =>{ return expression; }

// 当只有一个参数时,圆括号是可选的:
(singleParam) => { statements }
singleParam => { statements }

// 没有参数的函数应该写成一对圆括号。
() => { statements }
Copy after login

Return value representation

let add1 = (num1, num2) => {
  num1 + num2
};
let add2 = (num1, num2) => {
  return num1 + num2
};
let add3 = (num1, num2) => (num1 + num2);
let add4 = (num1, num2) => num1 + num2;

console.log(add1(2, 3));  // undefined
console.log(add2(2, 3)); // 5
console.log(add3(2, 3)); // 5
console.log(add4(2, 3)); // 5
Copy after login

Advanced

//加括号的函数体返回对象字面量表达式:
let func = () => ({foo: 'bar'})
console.log(func()); // {foo: 'bar'}


//支持剩余参数和默认参数
(param1, param2, ...rest) => { statements }
(param1 = defaultValue1, param2, …, paramN = defaultValueN) => {
statements }

//同样支持参数列表解构
let f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;
f();  // 6
Copy after login

this

Example code of ES6 arrow function practice

Best Practices

  • If you must use anonymous functions, or inline callback functions, use arrow functions. eslint: prefer-arrow-callback, arrow-spacing

why?The syntax is more concise, and this is more in line with expectations
If the function logic is quite complex, named functions should be used

// bad[1, 2, 3].map(function (x) {
  const y = x + 1;
  return x * y;});// good[1, 2, 3].map((x) => {
  const y = x + 1;
  return x * y;});
Copy after login
  • If the function body has only one statement, and the statement will not have side effects. Use the abbreviated form to return implicitly; or use the full form to return explicitly.
    eslint: arrow-parens, arrow-body-style
// bad
[1, 2, 3].map(number => {
  const nextNumber = number + 1;
  `A string containing the ${nextNumber}.`;
});

// good
[1, 2, 3].map(number => `A string containing the ${number}.`);

// good
[1, 2, 3].map((number) => {
  const nextNumber = number + 1;
  return `A string containing the ${nextNumber}.`;
});

// good
[1, 2, 3].map((number, index) => ({
  [index]: number,
}));

// No implicit return with side effects
function foo(callback) {
  const val = callback();
  if (val === true) {
    // Do something if callback returns true
  }
}

let bool = false;

// bad
foo(() => bool = true);

// good
foo(() => {
  bool = true;
});
Copy after login
  • When the expression occupies multiple lines, use parentheses to enhance readability

why? The beginning and end of the function are more clear

// bad['get', 'post', 'put'].map(httpMethod => Object.prototype.hasOwnProperty.call(
    httpMagicObjectWithAVeryLongName,
    httpMethod,
  ));// good['get', 'post', 'put'].map(httpMethod => (
  Object.prototype.hasOwnProperty.call(
    httpMagicObjectWithAVeryLongName,
    httpMethod,
  )));
Copy after login
  • If the function has only one parameter, omit the parentheses and omit the curly braces. Otherwise, always use the complete writing method to maintain consistency. eslint: arrow-parens
// bad[1, 2, 3].map((x) => x * x);// good[1, 2, 3].map(x => x * x);// good[1, 2, 3].map(number => (
  `A long string with the ${number}. It’s so long that we don’t want it to take up space on the .map line!`));// bad[1, 2, 3].map(x => {
  const y = x + 1;
  return x * y;});// good[1, 2, 3].map((x) => {
  const y = x + 1;
  return x * y;});
Copy after login
  • Use the unambiguous => syntax to distinguish it from =. eslint: no-confusing-arrow
// badconst itemHeight = item => item.height > 256 ? item.largeSize : item.smallSize;// badconst itemHeight = (item) => item.height > 256 ? item.largeSize : item.smallSize;// goodconst itemHeight = item => (item.height > 256 ? item.largeSize : item.smallSize);// goodconst itemHeight = (item) => {
  const { height, largeSize, smallSize } = item;
  return height > 256 ? largeSize : smallSize;
Copy after login

Simple conclusion

  • The arrow function cannot use new to create an instance of the constructor, but the ordinary function can (because the arrow function When it is created, the program will not create a construct method for it, that is, it has no construction ability and will be thrown away after use. Unlike ordinary functions that are reused, there is no need for a constructor prototype, that is, the prototype attribute will not be automatically generated)

  • The program will not create arguments objects for arrow functions

  • This in ordinary functions is dynamic, while this in arrow functions points to a tight The object that tightly wraps the arrow function (determined when defining)

  • The arrow function cannot change the value of this through bind, call, and apply, but it can still call these methods (just The value of this is not controlled by these methods)

[Related recommendations: javascript video tutorial, web front-end]

The above is the detailed content of Example code of ES6 arrow function practice. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
es6
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template