入门javascript_JavaScript中的ES6箭头功能入门

news/2024/7/5 21:15:58

入门javascript

介绍 (Introduction)

With ES6, there were many updates to the JavaScript, including the spread operator, object destructuring, new type of variables, and more. One of the most notable changes were arrow functions, a new and concise way to write functions. With arrow functions, you can define a readable and concise function in one line. In this article, we will walk through the basics of arrow functions and discuss their benefits.

使用ES6,对JavaScript进行了许多更新,包括散布运算符,对象解构,新型变量等。 最显着的变化之一是箭头函数 ,这是一种新的简洁的函数编写方式。 使用箭头功能,您可以在一行中定义一个可读且简洁的功能。 在本文中,我们将遍历箭头函数的基础知识并讨论它们的好处。

ES5中的功能 (Functions in ES5)

Let’s start by looking at how we defined functions with ES5 JavaScript. To 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 did it, the keyword function had 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, 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 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;

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 you wanted to print something to the console, you 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 using arrow functions with these methods, you can make complete array transformations in one line.

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

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, you 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. We would have this:

现在,让我们使用过滤器再做一次。 假设我们要过滤所有非偶数。 我们将有:

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

Again, no parenthesis and implicit return.

同样,没有括号和隐式返回。

带有箭头功能的“ this”绑定 (‘this’ Binding with Arrow Functions)

Let’s start with an example using an ES5 function definition inside of a person object:

让我们从在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属性。

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 properties by using this.

我们能够通过this关键字访问这些属性的原因是,当这些函数在对象内部定义时,它会自动绑定到对象本身。 因此,对于ES5函数,我们仍然可以使用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 function, 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, since the keyword this is not bound to the person object and doesn’t have a first and last variable to refer to.

在这种情况下,第一个和最后一个属性都将打印undefined ,因为关键字this并没有绑定到person对象,也没有第一个和最后一个变量要引用。

结论 (Conclusion)

Arrow functions are one of many new features of ES6 JavaScript. You will see them used more and more in examples and documentation, so it’s worth learning how they work. They can also significantly improve the conciseness and readability of your code.

箭头功能是ES6 JavaScript的许多新功能之一。 您将在示例和文档中看到它们越来越多地被使用,因此值得学习它们的工作原理。 它们还可以显着提高代码的简洁性和可读性。

翻译自: https://www.digitalocean.com/community/tutorials/getting-started-with-es6-arrow-functions-in-javascript

入门javascript


http://www.niftyadmin.cn/n/3649653.html

相关文章

[j2me]利用JLayerME-CLDC0.2播放MP3的试验[1]

有一个JLayerME-CLDC0.2,专门是用来在CLDC1.0/MIDP2.0上播放MP3文件以及获取mp3文件的位速/采样率的。JLayerME是自己做解码器解析MP3格式,然后自行转换为wav格式,这个格式是真机都支持的,然后再让Manager.createPlayer进行播放。…

前端:Angular框架与Ionic框架集成Html翻译pipe(管道)

在前端开发的时候经常会遇到页面显示的内容有HTML标记。默认是没有经过翻译的。集成翻译管道就可以正常显示内容。由于Angular与ionic集成的方法有点不,所以分开写。 一、Angular框架集成pipe 1、新建一个管道 新建命令:ng g pipe pipe/tohtml tohtml…

bem css_如何使用ITCSS和BEM解决大规模CSS瓶颈

bem css介绍 (Introduction) On frontend codebase projects, requirements and sometimes scopes can change frequently. When requirements change and you adjust the stylesheet or extend the styles of a selector in a particular page, such changes often affects ot…

Java基础---多态、抽象类、接口

2015-4-4 一、多态 1、定义:某一个事物,在不同时刻表现出来的不同状态。 2、多态的前提与体现: (1)要有继承关系; (2)要进行方法的重写; (3)要父…

移动开发:ionic框架的Android开发环境搭建

一、解决Eclipse与Android Studio的SDK冲突 Eclipse与Android Studio不能共用一套Android SDK,Android Studio会改变SDK的结构,eclipse不能正常使用Android SDK。但是我这个学期的两个课程都与Android开发有关。而且两个课程使用的开发工具都不一样。一边…

[流媒体]实例解析MMS流媒体协议,下载LiveMediaVideo[2][修正版本]

编写者日期关键词郑昀ultrapower2005-10-17mms streaming protocol ethereal 协议分析 流媒体为了改造mimms,我分析了SDP和流媒体服务器的来往包,看看我和他的实现到底存在哪些差异。如果你也开发流媒体下载应用,希望这个分析对你理解 “Micr…

react集成钉钉api_如何将Google Maps API集成到React应用程序中

react集成钉钉api介绍 (Introduction) This tutorial aims at integrating the google maps API to your React components and enabling you to display maps on your website. 本教程旨在将google maps API集成到您的React组件中,并使您能够在网站上显示地图。 先…

Android项目实战系列—基于博学谷(四)我的模块(上)

由于这个模块内容较多,篇幅较长,请耐心阅读。 “我”的模块分为四个部分 我的界面 设置界面 修改密码界面 设置密保和找回密码 一、“我”的界面 1、底部导航栏 (1)、导入界面图片 将底部导航栏所需图片main_course_icon.png、main_course…