용어 | 메서드 체이닝, 옵셔널 체이닝(JavaScript)

|

메서드 체이닝(Method Chaning)이란
연속적인 코드 줄에서 개체의 메서드를 반복적으로 호출하는 것을 의미합니다.

const store = {
    name: "yun",
    opacity: 30,
    peopleCount: 0,
    enter(n) {
        this.peopleCount += n;
    }
    leave(n) {        
        this.peopleCount -= n;
    }
}

store.enter(2);
store.leave(1);
store.enter(2);

두명의 손님이 들어오고, 1명이 손님이 나가고, 두명의 손님이 들어오는 모습입니다.

store.enter(2).leave(1).enter(2)

이 코드를 메서드 체이닝으로 활용하면 이렇게 됩니다.

활용

const Store = function () {
    this.name = "see you";
    this.opacity = 30;
    this.peopleCount = 0;
};

Store.prototype.enter = function (n) {
    this.peopleCount += n;
    return this;
};

Store.prototype.leave = function (n) {
    this.peopleCount -= n;
    return this;
};

Store.prototype.showPeopleCount = function (n) {
    console.log(this.peopleCount);
};

const thisStore = new Store();

thisStore.enter(2).leave(1).enter(2).showPeopleCount(); // 3

옵셔널 체이닝

ECMAScript2020 부터 도입된 옵셔널 체이닝 연산자는 ?. 으로 사용합니다.
좌항의 연산자가 null, undefined 인 경우 undefined 를 반환하고
그렇지 않으면 우항의 프로퍼티 참조를 이어갑니다.

let user = {}; // 주소 정보가 없는 사용자
alert( user?.address?.street ); // undefined

let user = {}; // 주소 정보가 없는 사용자
alert( user && user.address && user.address.street ); // undefined, 에러가 발생하지 않습니다.

과거에는 위와 같은 방식으로 작업을 했어야 했습니다.

null 병합 연산자

  • let foo = null ?? 'default' 와 같이 사용합니다
  • 좌항의 연산자가 null | undefined | falsy 인 경우 우항의 피연산자를 반환합니다.
    아닌경우 좌항의 피연산자를 반환합니다.

falsy : 거짓 같은 값
Boolean 문맥에서 false 로 평가됩니다.
(false , undefined , null , 0 , -0 , NaN , ”)

let foo = null ?? 'default string';
console.log(foo);

ES11(ECMAScript2020) 에서 도입되었습니다.

var foo = '' || 'default string';
console.log(foo);

이전 버전에서는 논리 연산자 || 를 사용한 단축 평가를 통해 변수에 기본값을 설정했습니다.

  • 값이 ” 이거나 0 인 경우 예기치 못한 동작이 발생할 수 있습니다.
    (falsy 를 구분하지 못함)

참조

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다

클릭하여 복사