매개 변수를받지 않는 countTimesCalled라는 화살표 함수를 만드는 작업을 맡았습니다. 호출 될 때마다 호출 된 횟수를 반환해야합니다. 함수는 완전히 독립적이어야합니다.
이것이 지금까지 제가 가지고있는 것입니다.이 라인을 따라 가고 싶지만 카운터 초기화 방법을 알 수 없습니다. 어떤 도움이라도 대단히 감사하겠습니다!
countTimesCalled= ()=> {
counter= 0;
if (counter== undefined){
counter= 1;
return(this.counter)
} else {
return(this.counter++)
}
- 답변 # 1
수를 추적하는 함수 자체에 속성을 연결할 수 있습니다.
const countTimesCalled= ()=> { if (!countTimesCalled.count) { countTimesCalled.count= 0; } return ++countTimesCalled.count; }; console.log(countTimesCalled()); console.log(countTimesCalled()); console.log(countTimesCalled());
화살표 함수없이 외부 클로저에 의존하지 않는 자체 참조를 만들 수 있습니다. let f= function g () {g.counter= (g.counter ?? 0) + 1; return g. counter; }; 에프(); 하자 h= f; f= 무효 0; h (); -함수가 포함 된 변수는 code를 깨지 않고 변경할 수 있습니다. 또는 항상 iife와 클로저를 사용할 수 있습니다.)
ASDFGerte2021-03-14 09:11:40@ASDFGerte 대답에 화살표 기능에 의존하는 것은 없습니다. countTimesCalled () {...} 함수로 동일한 작업을 수행 할 수 있습니다.
Barmar2021-03-14 09:11:40나는 그것을 "답변에 문제가있다"는 뜻이 아니라 단지 부수적 인 의미로 생각했다. 차이점은 클로저에서 외부 변수를 사용하지 않는 표현식을 얻을 수 있다는 것입니다. 심지어 function c () {if (! c.c) c.c= 0; return ++ c.c; } (함수 선언문으로) 누군가 c= void 0;을 할당 할 수 있으며 함수를 호출하면 throw됩니다.
ASDFGerte2021-03-14 09:11:40OP는 어쨌든 명시 적으로 화살표 기능을 요청했기 때문에 메모에 지나지 않습니다.
ASDFGerte2021-03-14 09:11:40 - 답변 # 2
함수 자체에 속성을 추가하여 사용 횟수를 절약 할 수 있습니다.
const countTimesCalled= ()=> { countTimesCalled.counter=!countTimesCalled.counter?0:countTimesCalled.counter; return ++countTimesCalled.counter ; };
또는 화살표 기능이 없습니다.
function countTimesCalled () { if (!this.counter) { this.counter= 0; } return ++this.counter; };
참고 :하지만 첫 번째 code가 가장 좋은 code입니다.
정말 도움이 됐어요 정말 감사합니다
Anna Botts2021-03-14 09:11:40@AnnaBotts ... abdo afage의 두 번째 버전은 this.counter를 통해 가장 깨끗한 코딩 스타일이 아닌 것으로 간주되는 전역 범위 내에서 카운터 변수를 생성하므로 절대 사용해서는 안됩니다.
Peter Seliger2021-03-14 09:11:40이 메모에 감사드립니다 :)
abdo afage2021-03-14 09:11:40@abdoafage ... 실제로 메모는 답변에서 두 번째 예제를 삭제하는 힌트로 볼 수 있습니다. 이 기반 접근 방식은 환경 화살표 함수 또는 함수 선언 /문 /표현에 도움이되지 않습니다.
Peter Seliger2021-03-14 09:11:40 - 답변 # 3
만들기 즉시 호출 된 함수 표현식그것을 계산 화살표 함수를 반환합니다. 이렇게하면 자신을 참조하는 함수가 필요하지 않으며 카운트가 외부와 완전히 분리됩니다.
const countTimesCalled= (count=> ()=> ++count)(0); console.log(countTimesCalled()); console.log(countTimesCalled()); console.log(countTimesCalled()); console.log(countTimesCalled()); console.log(countTimesCalled());
const countTimesCalled= ( count=> //<-------------<-------------<-------------+ ()=> ++count // | //^^^^^^^^^^^^^ gets assigned to `countTimesCalled` | )(0); //-->-passed as argument ->---------->----------+
확장 된 버전은 다음과 같습니다.
const countTimesCalled= ( ()=> { let count= 0; return ()=> { count += 1; return count; }; } )(); console.log(countTimesCalled()); console.log(countTimesCalled()); console.log(countTimesCalled()); console.log(countTimesCalled()); console.log(countTimesCalled());
클로저는 당신의 친구입니다. 당신의 기능을 반환하는 iife에 대해 생각 해보세요. 대안은 함수 자체에 카운터를 저장하는 것입니다.
ASDFGerte2021-03-14 09:11:40