When (and why) you should use ES6 arrow functions — and when you shouldn’t(如何正确使用es6箭头函数)

Arrow functions (also called “fat arrow functions”) are undoubtedly one of the more popular features of ES6. They introduced a new way of writing concise functions.
(箭头函数(也称为“胖箭头函数”)无疑是ES6最受欢迎的功能之一。 他们介绍了一种编写简洁函数的新方法)
Here is a function written in ES5 syntax:
(这是用ES5语法编写的函数)

function timesTwo(params) {
  return params * 2
}
timesTwo(4);  // 8

Now, here is the same function expressed as an arrow function:
(用箭头函数实现相同的功能)

var timesTwo = params => params * 2
timesTwo(4);  // 8

It’s much shorter! We are able to omit the curly braces and the return statement due to implicit returns (but only if there is no block — more on this below).
(它要短得多! 由于隐式的返回,我们能够省略花括号和return语句(但前提是没有块,请参见下文)。)

It is important to understand how the arrow function behaves differently compared to the regular ES5 functions.
(重要的是要了解箭头函数与常规ES5函数相比的行为方式不同)

Variations(变化)

One thing you will quickly notice is the variety of syntaxes available in arrow functions. Let’s run through some of the common ones:
(您很快会注意到的一件事是箭头函数中可用的语法多种多样。 我们来看一些常见的例子)
1. No parameters(无需参数)
If there are no parameters, you can place an empty parentheses before =>.
(如果没有参数,则可以在=>之前放置一个空括号。)

() => 42

In fact, you don’t even need the parentheses!
(实际上,您甚至都不需要括号!)

_ => 42

2. Single parameter (单一参数)
With these functions, parentheses are optional:
(使用这些函数,括号是可选的:)

x => 42  || (x) => 42

3. Multiple parameters(多个参数)
Parentheses are required for these functions:
(这些函数需要括号)

(x, y) => 42

4. Statements (as opposed to expressions) (语句(与表达式相反))
In its most basic form, a function expression produces a value, while a function statement performs an action.
(在最基本的形式中,函数表达式产生一个值,而函数语句执行一个动作。)
With the arrow function, it is important to remember that statements need to have curly braces. Once the curly braces are present, you always need to write return as well
(使用箭头函数时,重要的是要记住,语句需要使用花括号。 花括号出现后,您总是也需要写return)
Here is an example of the arrow function used with an if statement:
(这是与if语句一起使用的arrow函数的示例:)

var feedTheCat = (cat) => {
  if (cat === 'hungry') {
    return 'Feed the cat';
  } else {
    return 'Do not feed the cat';
  }
}

5. “Block body”(块区域)
If your function is in a block, you must also use the explicit return statement:
(如果函数在一个块中,则还必须使用显式的return语句:)

var addValues = (x, y) => {
  return x + y
}

6. Object literals(对象字面量)
If you are returning an object literal, it needs to be wrapped in parentheses. This forces the interpreter to evaluate what is inside the parentheses, and the object literal is returned.
(如果要返回对象,则需要将其放在括号中。 这样解析器就会解析括号中的内容,并返回对象。)

x =>({ y: x })

Syntactically anonymous 语法匿名
It is important to note that arrow functions are anonymous, which means that they are not named.
(重要的是要注意箭头函数是匿名的,这意味着它们没有被命名。)
This anonymity creates some issues:
(这种匿名性会带来一些问题:)

  1. Harder to debug
    (更难调试)
    When you get an error, you will not be able to trace the name of the function or the exact line number where it occurred.
    (出现错误时,将无法跟踪函数的名称或确切的行号。)
  2. No self-referencing
    (不能自引用)
    If your function needs to have a self-reference at any point (e.g. recursion, event handler that needs to unbind), it will not work.
    (如果您的函数在任何时候都需要一个自引用(例如,递归,需要解除绑定的事件处理程序),它将无法正常工作。)

Main benefit: No binding of ‘this’(主要优点:“ this”不受约束)
In classic function expressions, the this keyword is bound to different values based on the context in which it is called. With arrow functions however, this is lexically bound. It means that it usesthis from the code that contains the arrow function.
(在经典函数表达式中,this关键字根据调用上下文而绑定到不同的值。 但是,使用箭头函数时,这在词法上受约束。 这意味着它使用包含箭头函数的代码中的this。)
For example, look at the setTimeout function below:
(例如,看看下面的setTimeout函数)

// ES5
var obj = {
  id: 42,
  counter: function counter() {
    setTimeout(function() {
      console.log(this.id);
    }.bind(this), 1000);
  }
};

In the ES5 example, .bind(this) is required to help pass the this context into the function. Otherwise, by default this would be undefined.
(在ES5示例中,需要.bind(this)来帮助将此this上下文传递给函数。 否则,默认情况下这是未定义的。)

// ES6
var obj = {
  id: 42,
  counter: function counter() {
    setTimeout(() => {
      console.log(this.id);
    }, 1000);
  }
};

ES6 arrow functions can’t be bound to a this keyword, so it will lexically go up a scope, and use the value of this in the scope in which it was defined.
(ES6箭头函数无法绑定到this关键字,因此它将在词法上上升到一个作用域,并在定义它的作用域内使用this的值。)

When you should not use Arrow Functions
After learning a little more about arrow functions, I hope you understand that they do not replace regular functions.
(了解了更多关于箭头函数的知识之后,希望您能理解它们不会替代常规函数。)
Here are some instances where you probably wouldn’t want to use them:
(在某些情况下,不需要使用:)

  1. Object methods
    (对象内的方法)
    When you call cat.jumps, the number of lives does not decrease. It is because this is not bound to anything, and will inherit the value of this from its parent scope.
    (当调用jumps函数时,因为this无法绑定值,所以变量会从当前所在的父级作用域继承,因此值不会减少)
var cat = {
  lives: 9,
  jumps: () => {
    this.lives--;
  }
}
  1. Callback functions with dynamic context
    (具有动态作用域的回调函数)
    If you need your context to be dynamic, arrow functions are not the right choice. Take a look at this event handler below:
    (如果需要的是动态的作用域,箭头函数不是很好的选择,看下面的例子。)
var button = document.getElementById('press');
button.addEventListener('click', () => {
  this.classList.toggle('on');
});

If we click the button, we would get a TypeError. It is because this is not bound to the button, but instead bound to its parent scope.
(如果单击按钮,将收到TypeError。 这是因为这不绑定到按钮,而是绑定到其父作用域。)

  1. When it makes your code less readable
    (当它使您的代码可读性降低时)
    It is worth taking into consideration the variety of syntax we covered earlier. With regular functions, people know what to expect. With arrow functions, it may be hard to decipher what you are looking at straightaway.
    (值得考虑的是我们前面介绍的各种语法。 通过常规函数,人们知道会发生什么。 使用箭头函数,可能很难立即解读您正在查看的内容。)

When you should use them
Arrow functions shine best with anything that requires this to be bound to the context, and not the function itself.
(箭头函数最适合需要将其绑定到上下文,而不是函数本身。)
Despite the fact that they are anonymous, I also like using them with methods such as map and reduce, because I think it makes my code more readable. To me, the pros outweigh the cons.
(尽管它们是匿名的,但我也喜欢将它们与map和reduce一起使用,因为我认为它们使我的代码更具可读性。 对我而言,利弊大于弊。)
::https://medium.com/free-code-camp/when-and-why-you-should-use-es6-arrow-functions-and-when-you-shouldnt-3d851d7f0b26

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值