메서드 체이닝(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(); // 3ECMAScript2020 부터 도입된 옵셔널 체이닝 연산자는 ?. 으로 사용합니다.
좌항의 연산자가 null, undefined 인 경우 undefined 를 반환하고
그렇지 않으면 우항의 프로퍼티 참조를 이어갑니다.
let user = {}; // 주소 정보가 없는 사용자
alert( user?.address?.street ); // undefinedlet user = {}; // 주소 정보가 없는 사용자
alert( user && user.address && user.address.street ); // undefined, 에러가 발생하지 않습니다.과거에는 위와 같은 방식으로 작업을 했어야 했습니다.
let foo = null ?? 'default' 와 같이 사용합니다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);이전 버전에서는 논리 연산자 || 를 사용한 단축 평가를 통해 변수에 기본값을 설정했습니다.