클래스
다른 언어처럼 클래스 기반으로 동작하는 것이 아니라 여전히 프로토타입 기반으로 동작합니다. 프로토타입 기반 문법을 보기 위해 클래스로 바꾼 것이라고 이해하면 됩니다.
다음은 프로토타입 상속 예제 코드입니다.
var Human = function(type) {
this.type = type || 'human';
};
Human.isHuman = function(human) {
return human instanceof Human;
}
Human.prototype.breathe = function() {
alert('h-a-a-a-m');
}
var Zero = function(type, fistName, lastName) {
Human.apply(this, arguments);
this.firstName = fistName;
this.lastName = lastName;
}
Zero.prototype = Object.create(Human.prototype);
Zero.prototype.constructor = Zero; // 상속하는 부분
Zero.prototype.sayName = function() {
alert(this.firstName + " " + this.lastName);
};
var oldZero = new Zero('human', 'Zero', 'Cho');
Human.isHuman(oldZero); // true
위 코드를 클래스 기반 코드로 바꿔보겠습니다.
class Human {
constructor (type = "human") {
this.type = type;
}
static isHuman(human) {
return human instanceof Human;
}
breathe() {
alert('h-a-a-a-m');
}
}
class Zero extends Human {
constructor(type, firstName, lastName) {
super(type);
this.firstName = firstName;
this.lastName = lastName;
}
sayName() {
super.breathe();
alert(`${this.firstName} ${this.lastName}`);
}
}
const newZero = new Zero('human', 'Zero', 'Cho');
Human.isHuman(newZero); // true
전반적으로 class 안으로 그룹화된 것을 볼 수 있습니다.
생성자 함수는 constructor 안으로 들어갔고, Human, isHuman 같은 클래스 함수는 static 키워드로 전환되었습니다. 프로토타입 함수들로도 모두 class 블록 안에 포함되어 어떤 클래스 소속인지 보기 쉽습니다.
상속도 간단해져서 extends 키워드로 쉽게 상속이 가능합니다.