当前位置: 首页 > 工具软件 > Arrow > 使用案例 >

JavaScript Arrow函数教程

柳越
2023-12-01

Arrow functions were introduced in ES6 / ECMAScript 2015, and since their introduction they changed forever how JavaScript code looks (and works).

在ES6 / ECMAScript 2015中引入了Arrow函数,自从引入以来,它们就永远改变了JavaScript代码的外观(和工作方式)。

In my opinion this change was so welcoming that you now rarely see the usage of the function keyword in modern codebases. Although that has still its usage.

在我看来,这种更改是如此受欢迎,以至于您现在很少看到在现代代码库中使用function关键字的情况。 尽管那仍然有它的用法。

Visually, it’s a simple and welcome change, which allows you to write functions with a shorter syntax, from:

从视觉上看,这是一个简单而值得欢迎的更改,它使您可以使用较短的语法编写函数,这些函数来自:

const myFunction = function() {
  //...
}

to

const myFunction = () => {
  //...
}

If the function body contains just a single statement, you can omit the brackets and write all on a single line:

如果函数主体仅包含一条语句,则可以省略方括号并将所有内容写在一行上:

const myFunction = () => doSomething()

Parameters are passed in the parentheses:

参数在括号中传递:

const myFunction = (param1, param2) => doSomething(param1, param2)

If you have one (and just one) parameter, you could omit the parentheses completely:

如果有一个(只有一个)参数,则可以完全省略括号:

const myFunction = param => doSomething(param)

Thanks to this short syntax, arrow functions encourage the use of small functions.

由于这种简短的语法,箭头函数鼓励使用小函数

隐式回报 (Implicit return)

Arrow functions allow you to have an implicit return: values are returned without having to use the return keyword.

箭头函数使您可以隐式返回:无需使用return关键字即可返回值。

It works when there is a one-line statement in the function body:

当函数体中有单行语句时,它可以工作:

const myFunction = () => 'test'

myFunction() //'test'

Another example, when returning an object, remember to wrap the curly brackets in parentheses to avoid it being considered the wrapping function body brackets:

另一个示例,在返回对象时,请记住将花括号括在括号中,以避免将其视为包裹函数的主体括号:

const myFunction = () => ({ value: 'test' })

myFunction() //{value: 'test'}

如何this作品箭头功能 (How this works in arrow functions)

this is a concept that can be complicated to grasp, as it varies a lot depending on the context and also varies depending on the mode of JavaScript (strict mode or not).

this是一个很难理解的概念,因为它随上下文而变化很大,并且还取决于JavaScript的模式(是否为严格模式 )。

It’s important to clarify this concept because arrow functions behave very differently compared to regular functions.

弄清这个概念很重要,因为箭头函数的行为与常规函数非常不同。

When defined as a method of an object, in a regular function this refers to the object, so you can do:

当定义为对象的方法时,在常规函数中, this引用该对象,因此您可以执行以下操作:

const car = {
  model: 'Fiesta',
  manufacturer: 'Ford',
  fullName: function() {
    return `${this.manufacturer} ${this.model}`
  }
}

calling car.fullName() will return "Ford Fiesta".

调用car.fullName()将返回"Ford Fiesta"

The this scope with arrow functions is inherited from the execution context. An arrow function does not bind this at all, so its value will be looked up in the call stack, so in this code car.fullName() will not work, and will return the string "undefined undefined":

this箭头的功能范围从执行上下文继承 。 箭头函数根本不绑定this函数,因此将在调用堆栈中查找其值,因此在此代码中car.fullName()将不起作用,并将返回字符串"undefined undefined"

const car = {
  model: 'Fiesta',
  manufacturer: 'Ford',
  fullName: () => {
    return `${this.manufacturer} ${this.model}`
  }
}

Due to this, arrow functions are not suited as object methods.

因此,箭头功能不适合作为对象方法。

Arrow functions cannot be used as constructors either, when instantiating an object will raise a TypeError.

箭头函数也不能用作构造函数,在实例化对象时会引发TypeError

This is where regular functions should be used instead, when dynamic context is not needed.

当不需要动态上下文时 ,应在此处使用常规函数代替。

This is also a problem when handling events. DOM Event listeners set this to be the target element, and if you rely on this in an event handler, a regular function is necessary:

在处理事件时,这也是一个问题。 DOM事件监听器设置this是目标元素,如果依靠this在事件处理程序,一个普通的功能是必要的:

const link = document.querySelector('#link')
link.addEventListener('click', () => {
  // this === window
})
const link = document.querySelector('#link')
link.addEventListener('click', function() {
  // this === link
})

翻译自: https://flaviocopes.com/javascript-arrow-functions/

 类似资料: