JavaScript中的ES6箭头函数-入门

With ES6 JavaScript came many updates to the language including the spread operator, object destructuring, new type of variables, and more. On top of all those amazing features came arrow functions, a new and concise way to write functions. In this article, we will walk through the basics of arrow functions and discuss their benefits.

ES6带来了JavaScript的许多更新,包括传播运算符,对象解构,新型变量等。 在所有这些令人惊奇的功能之上,还有箭头功能 ,这是一种新颖简洁的编写功能的方法。 在本文中,我们将遍历箭头函数的基础知识并讨论它们的好处。

With arrow functions, you can define a readable and concise function in just one line!

使用箭头功能,您可以仅一行定义一个可读且简洁的功能!

ES5功能 ( ES5 Functions )

Let's start with looking at how we defined functions with ES5 JavaScript. To do define a function, it required the function keyword. For example, if we wanted to define a function that would multiply a number by two, it would look something like this.

让我们从如何使用ES5 JavaScript定义函数开始。 要定义函数,需要使用function关键字。 例如,如果我们想定义一个将数字乘以2的函数,则看起来像这样。

function multiplyByTwo(num){
    return num * 2;
}

We could also define the function and assign it to a variable if we wanted to.

如果需要,我们还可以定义函数并将其分配给变量。

const multiplyByTwo = function(num){
    return num * 2;
}

Regardless of which way you do it, the keyword function has to be included.

无论采用哪种方式,都必须包含关键字函数

您的第一个ES6箭头功能 ( Your First ES6 Arrow Function )

To create an arrow function, you don't need the keyword function. In fact, you basically remove that keyword and add an arrow right after the parameters but before the open curly bracket. It would look like this.

要创建箭头功能,不需要关键字function 。 实际上,您基本上删除了该关键字,并在参数之后但在大括号之前添加了一个箭头。 看起来像这样。

const multiplyByTwo = (num) => {
    return num * 2;
}

At this point, it doesn't look substantially different than the "old" way to do it, but we can make a few enhancements.

在这一点上,它看起来与“旧”方法没有本质区别,但是我们可以进行一些增强。

删除不必要的括号 ( Removing Unnecessary Parenthesis )

The parenthesis around the parameters are required if there are no parameters or more than one parameter. However, when your arrow function only has one parameter, you can leave out the parenthesis to simplify it a bit like so.

如果没有参数或一个以上参数,则必须在参数周围加上括号。 但是,当箭头函数只有一个参数时,可以省略括号以使其简化。

const multiplyByTwo = num => {
    return num * 2;
}

隐式回报 ( Implicit Return )

Often times, we write functions that return after just one line of code. With the "old" way of writing functions, the number of lines in the function didn't affect how you defined the function. With arrow functions, it can.

通常,我们编写仅在一行代码后返回的函数。 使用“旧的”编写函数的方法,函数中的行数不会影响定义函数的方式。 具有箭头功能,可以。

If the only thing you want to do in a function is a one-line return, you can use *implicit return *to greatly simplify your function. While using implicit return, you don't need the curly braces or the return keyword. It would look like this.

如果您要在函数中执行的唯一操作是单行返回,则可以使用* 隐式返回*大大简化函数。 使用隐式return时,不需要花括号或return关键字。 看起来像这样。

const multiplyByTwo = num => num * 2;

One thing to think about it is that you can still use the implicit return syntax even if you don't necessarily need to return anything. In other words, if the callers of your function are not expecting it to return anything, then having it return something doesn't matter.

需要考虑的一件事是,即使您不必返回任何内容,您仍然可以使用隐式返回语法。 换句话说,如果函数的调用者不希望它返回任何东西,那么让它返回一些东西并不重要。

For example, if I just wanted to print something to the console, I could use implicit return to shorten the length of the function.

例如,如果我只想在控制台上打印一些内容,则可以使用隐式return来缩短函数的长度。

const printName = (first, last) => console.log(`${first} ${last}`);

在地图和过滤器中使用箭头功能 ( Using Arrow Functions in Map and Filter )

One of the most common places you'll see arrow functions used are with JavaScript Array methods like map, reduce, filter, etc. By use arrow functions with these methods, you can make complete array transformations in just one line.

您将看到箭头功能最常使用的地方之一是JavaScript数组方法,例如map,reduce,filter等。通过将箭头函数与这些方法结合使用,您可以在一行中完成完整的数组转换。

For more background on JavaScript Array methods, check out Build JavaScript Array Methods From Scratch!

有关JavaScript数组方法的更多背景知识,请查看“ 从头开始构建JavaScript数组方法”

Let's look at two examples, one with map and one with filter. For the map version, let's say we want to convert an array by multiplying each number by two. It would look something like this.

让我们看两个示例,一个带有map,另一个带有filter。 对于地图版本,假设我们要通过将每个数字乘以2来转换数组。 看起来像这样。

const twodArray = [1,2,3,4].map( num => num * 2);

Notice with this arrow function, I left off the parenthesis (because there's only one parameter) and used implicit return. This kept the entire transformation to one line!

注意,使用此箭头功能,我省略了括号(因为只有一个参数),并使用了隐式返回。 这样就使整个转换只限于一行!

Now, let's do another with filter. Let's say we want to filter all numbers that are not even.

现在,让我们使用过滤器再做一次。 假设我们要过滤所有不为偶数的数字。

const filteredArray = [1,2,3,4].filter( num => num % 2 == 0);

Again, no parenthesis and implicit return. Super quick to make array transformations with just one!

同样,没有括号和隐式返回。 超级快速,只需一次即可进行数组转换!

带有箭头功能的“ This”绑定 ( 'This' Binding with Arrow Functions )

The conversation around the _this _keyword is definitely intermediate JavaScript, so you might need to do a little bit of additional research for this section. Regardless, let's start with an example using an ES5 function definition inside of a person object.

关于_this _keyword的对话肯定是中间JavaScript,因此您可能需要在本节中做一些其他研究。 无论如何,让我们从在person对象内部使用ES5函数定义的示例开始。

const person = {
    first: "James",
    last: "Quick",
    getName: function() {
        this.first + " " + this.last
    }
}

In this case, we created a person object with a first and last name as well as a getName() function that returns the full name of the person. Inside of the function, we are trying to reference the first and last properties, by calling this.first and this.last.

在这种情况下,我们创建了一个具有名字和姓氏的人员对象以及一个返回人员全名的getName()函数。 在函数内部,我们试图通过调用this.firstthis.last来引用first和last属性

When ES5 functions are defined in an object, 'this' refers to the object itself.

在对象中定义ES5函数时,“ this”是指对象本身。

The reason we are able to access those properties through the this keyword, is that when those functions are defined inside of an object, it is automatically bound to the object itself. Therefore, with ES5 functions, we can still reference the object propreties by using 'this'.

我们能够通过this关键字访问这些属性的原因是,当这些函数在对象内部定义时,它会自动绑定到对象本身。 因此,通过ES5函数,我们仍然可以使用' this '来引用对象属性。

Arrow functions don't bind anything to the keyword 'this'.

箭头函数不会将任何内容绑定到关键字“ this”。

However, when you use arrow functions, things change a bit. Arrow functions don't do any binding for the keyword this. Therefore, if we were to change the function definition to be an arrow functions, things wouldn't work.

但是,使用箭头功能时,情况会有所变化。 箭头函数不对关键字this进行任何绑定。 因此,如果我们将函数定义更改为箭头函数,则将无法正常工作。

const person = {
    first: "James",
    last: "Quick",
    getName: () => {
        return this.first + " " + this.last
    }
}

In this case, undefined would be printed for both the first and last property. The reason is since the keyword 'this' is not bound to the person object, it doesn't have a first and last variable to refer to.

在这种情况下,将为first和last属性同时打印undefined。 原因是因为关键字“ this”未绑定到person对象,所以没有第一个和最后一个变量要引用。

Understanding the difference between using this in arrow functions is really important!

了解箭头功能使用之间的差别是非常重要的!

结语 ( Wrap Up )

Arrow functions are one of many nifty little features of ES6 JavaScript. You will see them used more and more in examples and documentation, so it's worth learning how they work. Not to mention, they can significantly improve the conciseness and readability of your code!

箭头功能是ES6 JavaScript的许多漂亮的小功能之一。 您将在示例和文档中看到它们越来越多地被使用,因此值得学习它们的工作方式。 更不用说,它们可以极大地提高您代码的简洁性和可读性!

翻译自: https://scotch.io/tutorials/es6-arrow-functions-in-javascript-getting-started

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值