더북(TheBook)

2.1.6 클래스

클래스(class) 문법도 추가되었습니다. 하지만 다른 언어처럼 클래스 기반으로 동작하는 것이 아니라 여전히 프로토타입 기반으로 동작합니다. 프로토타입 기반 문법을 보기 좋게 클래스로 바꾼 것이라고 이해하면 됩니다.

다음은 프로토타입 상속 예제 코드입니다.

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, firstName, lastName) {
  Human.apply(this, arguments);
  this.firstName = firstName;
  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

Human 생성자 함수가 있고, 그 함수를 Zero 생성자 함수가 상속합니다. Zero 생성자 함수를 보면 상속받기 위한 코드가 상당히 난해함을 알 수 있습니다. Human.applyObject.create 부분이 상속받는 부분입니다.

신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.