es6-箭头函数默认传递_什么时候(为什么)应该使用ES6箭头功能-什么时候不应该使用...

es6-箭头函数默认传递

by Cynthia Lee

辛西娅·李(Cynthia Lee)

什么时候(为什么)应该使用ES6箭头功能-什么时候不应该使用 (When (and why) you should use ES6 arrow functions — and when you shouldn’t)

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}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.没有参数 (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.单参数 (2. Single parameter)

With these functions, parentheses are optional:

使用这些功能,括号是可选的:

x => 42  || (x) => 42
3.多个参数 (3. Multiple parameters)

Parentheses are required for these functions:

这些功能需要括号:

(x, y) => 42
4.陈述(相对于表达) (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.“方块体” (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.对象文字 (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

2.没有自我参照

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.

如果您的函数在任何时候都需要自引用(例如,递归,需要取消绑定的事件处理程序),它将无法正常工作。

主要好处:无需绑定“ this” (Main benefit: No binding of ‘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词法上受约束 。 这意味着,它使用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上下文传递给函数。 否则,默认情况下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.

当您调用cat.jumps ,生命不会减少。 这是因为this是不绑定到任何东西,将继承的值, this从它的父范围。

var cat = {
  lives: 9,
  jumps: () => {
    this.lives--;
  }
}

2. Callback functions with dynamic context

2.具有动态上下文的回调函数

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。 这是因为this不绑定到按钮,而是绑定到其父作用域。

3. When it makes your code less readable

3.当它使您的代码可读性降低时

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.

箭功能最闪耀与任何需要this绑定到上下文,而不是函数本身。

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.

尽管它们是匿名的,但我也喜欢将它们与诸如mapreduce方法一起使用,因为我认为它们使我的代码更具可读性。 对我而言,利弊大于弊。

Thanks for reading my article, and share if you liked it! Check out my other articles like How I built my Pomodoro Clock app, and the lessons I learned along the way, and Let’s demystify JavaScript’s ‘new’ keyword.

感谢您阅读我的文章,并分享您的喜欢! 查阅其他文章,例如“我如何构建Pomodoro Clock应用程序”,以及我在此过程中学到的课程 ,以及让我们揭开JavaScript的'new'关键字的神秘面纱

翻译自: https://www.freecodecamp.org/news/when-and-why-you-should-use-es6-arrow-functions-and-when-you-shouldnt-3d851d7f0b26/

es6-箭头函数默认传递

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值