es6 Arrow Functions에서 언제 'return'을 사용해야합니까?
새로운 es6 화살표 기능 은 return
일부 상황에서는 암시 적이 라고 말합니다 .
또한 표현식은 해당 함수의 내재 된 반환 값입니다.
return
es6 화살표 기능과 함께 사용해야하는 경우는 무엇 입니까?
Jackson은 비슷한 질문 으로 이것 에 부분적으로 대답했습니다 .
암시 적 반환 (블록이없는 경우에만).
- 한 줄짜리가 여러 줄로 확장되고 프로그래머가을 추가하는 것을 잊었을 때 오류가 발생합니다
return
.- 암시적인 반환은 구문 상 모호합니다.
(name) => {id: name}
객체를 반환합니다{id: name}
... 맞습니까? 잘못된. 를 반환합니다undefined
. 이 중괄호는 명시 적 블록입니다.id:
라벨입니다.
여기에 블록 정의를 추가합니다 .
블록 문 (또는 다른 언어의 복합 문)은 0 개 이상의 문을 그룹화하는 데 사용됩니다. 블록은 한 쌍의 중괄호로 구분됩니다.
예 :
// returns: undefined
// explanation: an empty block with an implicit return
((name) => {})()
// returns: 'Hi Jess'
// explanation: no block means implicit return
((name) => 'Hi ' + name)('Jess')
// returns: undefined
// explanation: explicit return required inside block, but is missing.
((name) => {'Hi ' + name})('Jess')
// returns: 'Hi Jess'
// explanation: explicit return in block exists
((name) => {return 'Hi ' + name})('Jess')
// returns: undefined
// explanation: a block containing a single label. No explicit return.
// more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label
((name) => {id: name})('Jess')
// returns: {id: 'Jess'}
// explanation: implicit return of expression ( ) which evaluates to an object
((name) => ({id: name}))('Jess')
// returns: {id: 'Jess'}
// explanation: explicit return inside block returns object
((name) => {return {id: name}})('Jess')
이 엄지 손가락 규칙을 이해합니다 ...
효과적으로 변형되는 함수 (한 줄의 인수 조작)의 경우 반환은 암시 적입니다.
후보자는 다음과 같습니다.
// square-root
value => Math.sqrt(value)
// sum
(a,b) => a+b
다른 작업 (블록이 필요한 라이너가 두 개 이상인 경우 반환은 명시 적이어야 함)
또 다른 경우가 있습니다.
React에서 기능 컴포넌트를 작성할 때 괄호를 사용하여 내재적으로 리턴 된 JSX를 랩핑 할 수 있습니다.
const FunctionalComponent = () => (
<div>
<OtherComponent />
</div>
);
화살표 함수를 사용하면 암시 적 반환을 할 수 있습니다. return
키워드 를 사용하지 않고도 값이 반환됩니다 .
함수 본문에 온라인 문장이있을 때 작동합니다.
const myFunction = () => 'test'
console.log(myFunction()) //'test'
Another example, 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'})
console.log(myFunction()) //{value: 'test'}
Here's another case that gave me some trouble.
// the "tricky" way
const wrap = (foo) => (bar) => {
if (foo === 'foo') return foo + ' ' + bar;
return 'nofoo ' + bar;
}
Here we define a function returning an anonymous function.The "tricky" bit is that the function body for the outer function (the part begining with (bar) => ...) visually looks like a "block", but it's not. Since it's not, implicit return kicks in.
Here's how wrap would execute:
// use wrap() to create a function withfoo()
const withfoo = wrap('foo');
// returns: foo bar
console.log(withfoo('bar'));
// use wrap() to create a function withoutfoo()
const withoutfoo = wrap('bar');
// returns: nofoo bar
console.log(withoutfoo('bar'));
The way I unpacked this to make sure I understood it was to "unarrowify" the functions.
Here's the semantic equivalent of the first code block, simply making the body of wrap() do an explicit return. This definition produces the same results as above. This is where the dots connect. Compare the first code block above with the one below, and it's clear that an arrow function itself is treated as an expression, not a block, and has the implied return.
// the explicit return way
const wrap = (foo) => {
return (bar) => {
if (foo === 'foo') return foo + ' ' + bar;
return 'nofoo ' + bar;
}
}
The fully unarrowified version of wrap would be like this, which while not as compact as the fat arrowed up version, seems a lot easier to comprehend.
// the "no arrow functions" way
const wrap = function(foo) {
return function(bar) {
if (foo === 'foo') return foo + ' ' + bar;
return 'nofoo ' + bar;
};
};
In the end, for others that may have to read my code, and future me, I think I'd prefer to go the non arrow version which can be comprehended visually at first glance, rather than the arrow one which takes a fair bit of thought (and in my case experimentation) to grok.
참고URL : https://stackoverflow.com/questions/28889450/when-should-i-use-return-in-es6-arrow-functions
'Programing' 카테고리의 다른 글
AWS S3 버킷 이름을 바꾸는 방법 (0) | 2020.06.26 |
---|---|
파이썬에서 인터페이스를 어떻게 구현합니까? (0) | 2020.06.25 |
vs (0) | 2020.06.25 |
FromBody와 FromUri를 지정해야하는 이유는 무엇입니까? (0) | 2020.06.25 |
IEnumerable (0) | 2020.06.25 |