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' ]