JS/Javascript

[javascript] 메서드 체이닝(Method Chaining)

ui-o 2025. 9. 3. 16:55
반응형

메서드 체이닝(Method Chaining)

  • 정의 : 한 객체에서 여러 메서드를 연속으로 호출하는 기법
  • 한 메서드가 호출된 후 자신(객체)을 반환해서 다음 메서드를 이어서 호출할 수 있는 구조
  • 문자열, 배열, 커스텀 객체 등 다양한 곳에서 활용 가능
  • 각 메서드는 반드시 객체 자신(this) 또는 메서드 체이닝 가능한 값을 반환해야 체이닝이 가능함'
장점 단점
코드가 간결해짐 한 메서드라도 잘못되면 전체 체인 실패
객체를 여러 번 참조할 필요 없음 디버깅 시 어느 단계에서 문제 생겼는지 찾기 어려움
연속 연산이 직관적으로 표현됨 체이닝만 의존하면 가독성이 떨어질 수 있음
// ex)
object.method1().method2().method3();

체이닝 활용 

문자열 체이닝 활용

  • 활용: URL slug 생성, 사용자 입력 정리 등..
// ex)
const input = "   hello world   ";

const formatted = input
  .trim()            // 앞뒤 공백 제거
  .toLowerCase()     // 소문자로 변환
  .replace(/\s+/g, "-"); // 공백을 하이픈으로 변경

console.log(formatted); // "hello-world"

배열 체이닝 활용

  • 활용: 데이터 가공, 통계, UI 렌더링 전 처리 ...
// ex)
const users = [
  { name: "Alice", age: 25, active: true },
  { name: "Bob", age: 30, active: false },
  { name: "Charlie", age: 22, active: true }
];

const activeUserNames = users
  .filter(user => user.active)       // 활성 사용자만
  .map(user => user.name)            // 이름만 추출
  .sort();                           // 알파벳 순 정렬

console.log(activeUserNames); // ["Alice", "Charlie"]

객체 체이닝

  • 활용 : DOM 조작 시 jQuery 스타일 체이닝, UI 컴포넌트 설정...
// ex)
const $button = {
  el: document.querySelector("#myButton"),
  setText(text) {
    this.el.textContent = text;
    return this;
  },
  setColor(color) {
    this.el.style.color = color;
    return this;
  },
  onClick(handler) {
    this.el.addEventListener("click", handler);
    return this;
  }
};

$button
  .setText("클릭해!")
  .setColor("blue")
  .onClick(() => alert("버튼 클릭됨!"));
반응형