2021-06-15 00:49:18 -07:00
|
|
|
---
|
|
|
|
id: 587d7b8b367417b2b2512b50
|
2021-07-21 20:53:20 +05:30
|
|
|
title: Escrever funções declarativas concisas com ES6
|
2021-06-15 00:49:18 -07:00
|
|
|
challengeType: 1
|
|
|
|
forumTopicId: 301224
|
|
|
|
dashedName: write-concise-declarative-functions-with-es6
|
|
|
|
---
|
|
|
|
|
|
|
|
# --description--
|
|
|
|
|
2021-07-14 21:02:51 +05:30
|
|
|
Ao definir funções dentro de objetos em ES5, nós temos de usar a palavra-chave `function` como se segue:
|
2021-06-15 00:49:18 -07:00
|
|
|
|
|
|
|
```js
|
|
|
|
const person = {
|
|
|
|
name: "Taylor",
|
|
|
|
sayHello: function() {
|
|
|
|
return `Hello! My name is ${this.name}.`;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
```
|
|
|
|
|
2021-07-14 21:02:51 +05:30
|
|
|
Com ES6, você pode remover a palavra-chave `function` e dois pontos ao definir funções em objetos. Aqui está um exemplo dessa sintaxe:
|
2021-06-15 00:49:18 -07:00
|
|
|
|
|
|
|
```js
|
|
|
|
const person = {
|
|
|
|
name: "Taylor",
|
|
|
|
sayHello() {
|
|
|
|
return `Hello! My name is ${this.name}.`;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
```
|
|
|
|
|
|
|
|
# --instructions--
|
|
|
|
|
2021-07-14 21:02:51 +05:30
|
|
|
Refatore a função `setGear` dentro do objeto `bicycle` para usar a sintaxe curta descrita acima.
|
2021-06-15 00:49:18 -07:00
|
|
|
|
|
|
|
# --hints--
|
|
|
|
|
2021-07-14 21:02:51 +05:30
|
|
|
Expressão tradicional de função não deve ser usado.
|
2021-06-15 00:49:18 -07:00
|
|
|
|
|
|
|
```js
|
|
|
|
(getUserInput) => assert(!code.match(/function/));
|
|
|
|
```
|
|
|
|
|
2021-07-14 21:02:51 +05:30
|
|
|
`setGear` deve ser uma função declarativa.
|
2021-06-15 00:49:18 -07:00
|
|
|
|
|
|
|
```js
|
|
|
|
assert(
|
|
|
|
typeof bicycle.setGear === 'function' && code.match(/setGear\s*\(.+\)\s*\{/)
|
|
|
|
);
|
|
|
|
```
|
|
|
|
|
2021-07-14 21:02:51 +05:30
|
|
|
`bicycle.setGear(48)` deve alterar o valor de `gear` para 48.
|
2021-06-15 00:49:18 -07:00
|
|
|
|
|
|
|
```js
|
|
|
|
assert(new bicycle.setGear(48).gear === 48);
|
|
|
|
```
|
|
|
|
|
|
|
|
# --seed--
|
|
|
|
|
|
|
|
## --seed-contents--
|
|
|
|
|
|
|
|
```js
|
|
|
|
// Only change code below this line
|
|
|
|
const bicycle = {
|
|
|
|
gear: 2,
|
|
|
|
setGear: function(newGear) {
|
|
|
|
this.gear = newGear;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
// Only change code above this line
|
|
|
|
bicycle.setGear(3);
|
|
|
|
console.log(bicycle.gear);
|
|
|
|
```
|
|
|
|
|
|
|
|
# --solutions--
|
|
|
|
|
|
|
|
```js
|
|
|
|
const bicycle = {
|
|
|
|
gear: 2,
|
|
|
|
setGear(newGear) {
|
|
|
|
this.gear = newGear;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
bicycle.setGear(3);
|
|
|
|
```
|