File tree Expand file tree Collapse file tree 1 file changed +81
-0
lines changed
docs/playground/ko/JavaScript/Functions with JavaScript Expand file tree Collapse file tree 1 file changed +81
-0
lines changed Original file line number Diff line number Diff line change 1+ //// { order: 2, compiler: { esModuleInterop: true } }
2+
3+ // 함수 체이닝 API는 JavaScript에서 흔한 패턴으로,
4+ // JavaScript 의 중첩 특성으로 인해
5+ // 중간값을 줄이고 가독성을 높혀
6+ // 코드를 집중시킬 수 있습니다.
7+
8+ // 체이닝으로 동작하는 흔한 API는 jQuery입니다.
9+ // DefinitelyTyped의 타입과 함께 사용한
10+ // jQuery 예시입니다.:
11+
12+ import $ from "jquery" ;
13+
14+ // jQuery API 사용 예시:
15+
16+ $ ( "#navigation" ) . css ( "background" , "red" ) . height ( 300 ) . fadeIn ( 200 ) ;
17+
18+ // 위 라인에 점을 추가해보면,
19+ // 긴 함수 리스트를 보게 될 것입니다.
20+ // 이 패턴은 JavaScript에서 쉽게 재현할 수 있습니다.
21+ // 핵심은 반드시 항상 같은 오브젝트를 반환하는 것입니다.
22+
23+ // 여기 체이닝 API를 만드는 API 예시가 있습니다.
24+ // 핵심은 내부 상태를 파악하고 있는 외부 함수와
25+ // 항상 자신을 반환하는 API를
26+ // 노출하는 오브젝트를 갖는 것입니다.
27+
28+ const addTwoNumbers = ( start = 1 ) => {
29+ let n = start ;
30+
31+ const api = {
32+ // API에 있는 각 함수를 실행하세요
33+ add ( inc : number = 1 ) {
34+ n += inc ;
35+ return api ;
36+ } ,
37+
38+ print ( ) {
39+ console . log ( n ) ;
40+ return api ;
41+ } ,
42+ } ;
43+ return api ;
44+ } ;
45+
46+ // jQuery에서 본 것처럼
47+ // 같은 스타일의 API를 허용:
48+
49+ addTwoNumbers ( 1 ) . add ( 3 ) . add ( ) . print ( ) . add ( 1 ) ;
50+
51+ // 클래스를 사용하는 비슷한 예시:
52+
53+ class AddNumbers {
54+ private n : number ;
55+
56+ constructor ( start = 0 ) {
57+ this . n = start ;
58+ }
59+
60+ public add ( inc = 1 ) {
61+ this . n = this . n + inc ;
62+ return this ;
63+ }
64+
65+ public print ( ) {
66+ console . log ( this . n ) ;
67+ return this ;
68+ }
69+ }
70+
71+ // 여기에서 동작:
72+
73+ new AddNumbers ( 2 ) . add ( 3 ) . add ( ) . print ( ) . add ( 1 ) ;
74+
75+ // 이 예시는 JavaScript 패턴에
76+ // 도구를 제공하는 방법을 제공하기 위해서
77+ // TypeScript 타입 추론을 사용했습니다.
78+
79+ // 더 많은 예시:
80+ //
81+ // - example:code-flow
You can’t perform that action at this time.
0 commit comments