캐스케이딩이라고도 하는 연결 메서드는 하나의 연속적인 코드 줄에서 객체에 대해 한 메서드를 반복적으로 호출하는 것을 의미합니다. 메서드 체인이 반복을 방지하는 데 도움이 되는 예를 살펴보겠습니다.
예시
예를 들어 다음 클래스 자동차를 가져오십시오. -
class Car {
constructor() {
this.wheels = 4
this.doors = 4
this.topSpeed = 100
this.feulCapacity = "400 Litres"
}
setWheels(w) {
this.wheels = w
}
setDoors(d) {
this.doors = d
}
setTopSpeed(t) {
this.topSpeed = t
}
setFeulCapacity(fc) {
this.feulCapacity = fc
}
displayCarProps() {
console.log(`Your car has ${this.wheels} wheels,\
${this.doors} doors with a top speed of ${this.topSpeed}\
and feul capacity of ${this.feulCapacity}`)
}
}
let sportsCar = new Car();
sportsCar.setDoors(2)
sportsCar.setTopSpeed(250)
sportsCar.setFeulCapacity("600 Litres")
sportsCar.displayCarProps() 출력
Your car has 4 wheels,2 doors with a top speed of 250and feul capacity of 600 Litres
얼마나 많은 스포츠카가 불필요하게 반복되는지 봅니까? 메서드 체이닝을 사용하여 제거할 수 있습니다. 그렇게 하려면 setter가 값을 설정하도록 하는 대신 끝에 이것을 반환합니다. 이렇게 하면 개체에 대한 작업을 수행할 수 있습니다. 이 변경을 수행한 후 코드는 다음과 같습니다. -
class Car {
constructor() {
this.wheels = 4
this.doors = 4
this.topSpeed = 100
this.feulCapacity = "400 Litres"
}
setWheels(w) {
this.wheels = w;
return this;
}
setDoors(d) {
this.doors = d;
return this;
}
setTopSpeed(t) {
this.topSpeed = t;
return this;
}
setFeulCapacity(fc) {
this.feulCapacity = fc;
return this;
}
displayCarProps() {
console.log(`Your car has ${this.wheels} wheels,\
${this.doors} doors with a top speed of ${this.topSpeed}\
and feul capacity of ${this.feulCapacity}`)
}
} 이제 더 읽기 쉽고 덜 반복적인 코드로 car 객체를 생성하는 부분을 변경할 수 있습니다. −
예시
let sportsCar = new Car()
.setDoors(2)
.setTopSpeed(250)
.setFeulCapacity("600 Litres")
.displayCarProps() 출력
Your car has 4 wheels,2 doors with a top speed of 250and feul capacity of 600 Litres
메서드 체이닝은 개체를 반복하여 흐름을 계속해서 끊지 않고 메서드를 통해 개체에 대해 작업할 수 있으므로 유창한 인터페이스라고도 합니다.