quiz(js): improve arrow function question
This commit is contained in:
parent
d24b5d8cfb
commit
15525bfe89
|
|
@ -3,4 +3,48 @@ title: Can you offer a use case for the new arrow => function syntax?
|
|||
subtitle: How does this new syntax differ from other functions?
|
||||
---
|
||||
|
||||
One obvious benefit of arrow functions is to simplify the syntax needed to create functions, without a need for the `function` keyword. The `this` within arrow functions is also bound to the enclosing scope which is different compared to regular functions where the `this` is determined by the object calling it. Lexically-scoped `this` is useful when invoking callbacks especially in React components.
|
||||
The `=>` function syntax, also known as "arrow functions," is a feature introduced in ECMAScript 6 (ES6) for JavaScript. It provides a more concise way to write functions and also has some differences in how `this` behaves compared to traditional function expressions. Here's a simple use case to illustrate its utility:
|
||||
|
||||
## Use case: filtering an array
|
||||
|
||||
Imagine you have an array of numbers, and you want to filter out all the numbers that are less than 10. Using traditional function syntax and the new arrow function syntax, you can achieve this in the following ways:
|
||||
|
||||
### Traditional functions syntax
|
||||
|
||||
```javascript
|
||||
const numbers = [1, 5, 10, 15, 20];
|
||||
const filteredNumbers = numbers.filter(function (number) {
|
||||
return number >= 10;
|
||||
});
|
||||
|
||||
console.log(filteredNumbers); // Output: [10, 15, 20]
|
||||
```
|
||||
|
||||
### Arrow function syntax
|
||||
|
||||
```javascript
|
||||
const numbers = [1, 5, 10, 15, 20];
|
||||
const filteredNumbers = numbers.filter((number) => number >= 10);
|
||||
|
||||
console.log(filteredNumbers); // Output: [10, 15, 20]
|
||||
```
|
||||
|
||||
## Advantages of arrow functions
|
||||
|
||||
1. **Conciseness**: Arrow functions are more concise, making your code shorter and easier to read.
|
||||
1. **`this` Behavior**: Arrow functions do not have their own `this`. Instead, they inherit `this` from the parent scope at the time they are defined. This is particularly useful in scenarios where you are dealing with callbacks and want to retain the context of `this`.
|
||||
1. **Implicit Return**: If the function body consists of a single expression, arrow functions allow you to omit the `return` keyword and the curly braces.
|
||||
|
||||
## When to use arrow functions
|
||||
|
||||
- When you need a quick, one-line function.
|
||||
- In callback functions where you want to preserve the lexical scope of `this`.
|
||||
- When working with higher-order functions like `map`, `filter`, `reduce`, etc.
|
||||
|
||||
## When not to use arrow functions
|
||||
|
||||
- **Methods in objects**: Arrow functions do not have their own `this` context, which can lead to unexpected behavior in object methods.
|
||||
- **As constructors**: Arrow functions cannot be used as constructors and will throw an error if used with the `new` keyword.
|
||||
- **When you need to use function hoisting**: Arrow functions are not hoisted, unlike traditional function declarations.
|
||||
|
||||
Arrow functions are a powerful addition to JavaScript, simplifying function syntax and addressing some common pitfalls associated with the `this` keyword in traditional functions. They are especially useful in modern JavaScript development patterns.
|
||||
|
|
|
|||
|
|
@ -3,4 +3,48 @@ title: Você pode oferecer um caso de uso para a nova sintaxe de arrow function
|
|||
subtitle: Como essa nova sintaxe difere de outras funções?
|
||||
---
|
||||
|
||||
Um benefício óbvio das arrow functions é simplificar a sintaxe necessária para criar funções, sem a necessidade da palavra-chave `function`. O `this` dentro das arrow functions também está ligado ao escopo que é diferente comparado a funções regulares onde o `this` é determinado pelo objeto que o chama. `this` com escopo léxico é útil ao invocar callbacks, especialmente em componentes React.
|
||||
A sintaxe de função `=>`, também conhecida como "funções de seta", é um recurso introduzido no ECMAScript 6 (ES6) para o JavaScript. Ela fornece uma maneira mais concisa de escrever funções e também apresenta algumas diferenças em relação ao comportamento do `this` em comparação com expressões de função tradicionais. Aqui está um caso de uso simples para ilustrar sua utilidade:
|
||||
|
||||
## Caso de Uso: filtrando um array
|
||||
|
||||
Imagine que você tenha um array de números e queira filtrar todos os números menores que 10. Usando a sintaxe de função tradicional e a nova sintaxe de função de seta, você pode realizar isso das seguintes maneiras:
|
||||
|
||||
### Sintaxe de função tradicional
|
||||
|
||||
```javascript
|
||||
const numbers = [1, 5, 10, 15, 20];
|
||||
const numbersFiltrados = numbers.filter(function (number) {
|
||||
return number >= 10;
|
||||
});
|
||||
|
||||
console.log(numbersFiltrados); // Saída: [10, 15, 20]
|
||||
```
|
||||
|
||||
### Sintaxe de função de seta
|
||||
|
||||
```javascript
|
||||
const numbers = [1, 5, 10, 15, 20];
|
||||
const numbersFiltrados = numbers.filter((number) => number >= 10);
|
||||
|
||||
console.log(numbersFiltrados); // Saída: [10, 15, 20]
|
||||
```
|
||||
|
||||
## Vantagens das funções de seta
|
||||
|
||||
1. **Concisão**: As funções de seta são mais concisas, tornando seu código mais curto e mais fácil de ler.
|
||||
1. **Comportamento do `this`**: As funções de seta não possuem seu próprio `this`. Em vez disso, elas herdam o `this` do escopo pai no momento em que são definidas. Isso é particularmente útil em cenários em que você está lidando com callbacks e deseja manter o contexto do `this`.
|
||||
1. **Retorno Implícito**: Se o corpo da função consistir em uma única expressão, as funções de seta permitem omitir a palavra-chave `return` e as chaves.
|
||||
|
||||
## Quando usar funções de seta
|
||||
|
||||
- Quando você precisa de uma função rápida de uma única linha.
|
||||
- Em funções de retorno de chamada (callbacks) onde você deseja preservar o escopo léxico do `this`.
|
||||
- Ao trabalhar com funções de ordem superior como `map`, `filter`, `reduce`, etc.
|
||||
|
||||
## Quando não usar funções de seta
|
||||
|
||||
- **Métodos em objetos**: As funções de seta não têm seu próprio contexto `this`, o que pode levar a comportamentos inesperados em métodos de objetos.
|
||||
- **Como construtores**: As funções de seta não podem ser usadas como construtores e gerarão um erro se usadas com a palavra-chave `new`.
|
||||
- **Quando você precisa de hoisting de função**: As funções de seta não são içadas (hoisted), ao contrário das declarações de função tradicionais.
|
||||
|
||||
As funções de seta são uma adição poderosa ao JavaScript, simplificando a sintaxe das funções e abordando algumas armadilhas comuns associadas à palavra-chave `this` em funções tradicionais. Elas são especialmente úteis nos padrões de desenvolvimento JavaScript modernos.
|
||||
|
|
|
|||
|
|
@ -3,4 +3,48 @@ title: 您可以为新箭头函数语法提供一个用例吗?
|
|||
subtitle: 这个新语法与其他函数有什么不同?
|
||||
---
|
||||
|
||||
箭头函数的一个明显好处是简化创建函数所需的语法,而不需要 `function` 关键字。 箭头函数中的`this`也与正常函数不同,而正常函数`this`是由调用对象决定的。 在调用回调时,特别是在React组件中,词法范围的`this`非常有用。
|
||||
`=>` 函数语法,也被称为 "箭头函数",是在 ECMAScript 6(ES6)中引入的 JavaScript 功能。它提供了一种更简洁的编写函数的方式,并且在 `this` 的行为方面与传统函数表达式有一些不同。下面通过一个简单的用例来说明它的实用性:
|
||||
|
||||
## 用例:筛选数组
|
||||
|
||||
假设你有一个包含数字的数组,你想筛选出所有小于 10 的数字。你可以使用传统的函数语法和新的箭头函数语法来实现这一目标,如下所示:
|
||||
|
||||
### 传统函数语法
|
||||
|
||||
```js
|
||||
const numbers = [1, 5, 10, 15, 20];
|
||||
const filteredNumbers = numbers.filter(function (number) {
|
||||
return number >= 10;
|
||||
});
|
||||
|
||||
console.log(filteredNumbers); // 输出: [10, 15, 20]
|
||||
```
|
||||
|
||||
### 箭头函数语法
|
||||
|
||||
```js
|
||||
const numbers = [1, 5, 10, 15, 20];
|
||||
const filteredNumbers = numbers.filter((number) => number >= 10);
|
||||
|
||||
console.log(filteredNumbers); // 输出: [10, 15, 20]
|
||||
```
|
||||
|
||||
## 箭头函数的优点
|
||||
|
||||
1. **简洁性**:箭头函数更加简洁,使你的代码更短且易于阅读。
|
||||
1. **`this` 行为**:箭头函数没有自己的 `this`。相反,它们继承自它们在定义时的父级作用域中的 `this`。这在处理回调并希望保留 `this` 上下文的情况下特别有用。
|
||||
1. **隐式返回**:如果函数体只包含一个表达式,箭头函数允许省略 `return` 关键字和花括号。
|
||||
|
||||
## 何时使用箭头函数
|
||||
|
||||
- 当你需要一个快速的、单行的函数时。
|
||||
- 在回调函数中,当你想要保留 `this` 的词法作用域时。
|
||||
- 在使用 `map`、`filter`、`reduce` 等高阶函数时。
|
||||
|
||||
## 何时不要使用箭头函数
|
||||
|
||||
- **对象方法**:箭头函数没有自己的 `this` 上下文,在对象方法中可能会导致意外行为。
|
||||
- **作为构造函数**:箭头函数不能作为构造函数使用,如果使用 `new` 关键字会引发错误。
|
||||
- **当你需要使用函数提升**:与传统的函数声明不同,箭头函数不会提升。
|
||||
|
||||
箭头函数是 JavaScript 的一个强大补充,简化了函数语法,并解决了传统函数中 `this` 关键字的一些常见问题。它们在现代 JavaScript 开发模式中特别有用。
|
||||
|
|
|
|||
Loading…
Reference in New Issue