메서드 체이닝(Method Chaining)

he0o0nje·2024년 1월 17일
0

Javascript

목록 보기
15/15

✨메서드 체이닝(Method Chaining)

  • 메서드가 객체를 반환하게 되면 메서드의 반환 값인 객체를 통해 또 다른 함수를 호출할 수 있다. 이러한 프로그래밍 패턴을 메서드 체이닝(Method Chaining)이라 부른다.
  • 메서드 체이닝 아닌 코드
const Exercise = function() {
	this.name = '';
  	this.hour = 0;
  	this.person = [];
}
Exercise.prototype.setName = function(name) {
	this.name = name;
}
Exercise.prototype.setHour = function(hour) {
	this.hour = hour;
}
Exercise.prototype.getPerson = function(...person) {
	this.person.push = (...person);
}
Exercise.prototype.getInfo = function() {
  	console.log(this.name);
  	console.log(this.hour);
  	console.log(this.person);
}

// instance 생성
const GX = new Exercise
GX.setName('BB');
GX.setHour(2);
GX.getPerson('heonje', 'ajin');
GX.getInfo();
// BB, 2, [ 'heonje', 'ajin' ]

위 코드에 아래와 같이 메서드를 연결하면 에러 발생

GX.setName('BB').setHour(2).getPerson('heonje', 'ajin').getInfo();
// Uncaught TypeError: Cannot read property 'setHour' of undefined

setName 메서드가 리턴하는 값이 없기 때문에 GX.setName('BB'); 자체는 undefined가 된다. (그래서 undefined의 setHour 메서드를 읽을 수 없다는 에러 메시지가 나오는 것)

  • 메서드 체이닝으로 변환
const Exercise = function() {
	this.name = '';
  	this.hour = 0;
  	this.person = [];
}
Exercise.prototype.setName = function(name) {
	this.name = name;
  	return this; // 자기 자신(객체)을 리턴
}
Exercise.prototype.setHour = function(hour) {
	this.hour = hour;
  	return this; // 자기 자신(객체)을 리턴
}
Exercise.prototype.getPerson = function(...person) {
	this.person.push = (...person);
  	return this; // 자기 자신(객체)을 리턴
}
Exercise.prototype.getInfo = function() {
  	console.log(this.name);
  	console.log(this.hour);
  	console.log(this.person);
}

// instance 생성
const GX = new Exercise
GX.setName('BB').setHour(2).getPerson('heonje', 'ajin').getInfo();
// BB, 2, [ 'heonje', 'ajin' ]

0개의 댓글