07 클래스
7.3 클래스 상속
자바스크립트에서 클래스 상속을 구현했다는 것은 결국 프로토타입 체이닝을 잘 연결한 것으로 이해하면 된다.
ES5까지의 자바스크립트에는 클래스가 없다.
ES6에서 클래스가 도입됐지만 역시나 prototype을 기반으로 한 것이다.
하위 클래스로 삼을 생성자 함수의 prototype에 상위 클래스의 인스턴스를 부여하는 것만으로도 기본적인 메서드 상속은 가능하지만, 다양한 문제가 발생할 여지가 있어 구조적으로 안전성이 떨어진다.
var Rectangle = function (width, height) {
this.width = width
this.height = height
}
Rectangle.prototype.getArea = function () {
return this.width * this.height
}
var rect = new Rectangle(3, 4)
console.log(rect.getArea()) // 12
// Rectangle을 상속하는 Square 클래스
var Square = function (width) {
Rectangle.call(this, width, width)
}
Square.prototype = new Rectangle()
var sq = new Square(5)
console.log(sq.getArea()) // 25
var rect2 = new sq.constructor(2, 3)
console.log(rect2) // Rectangle { width: 2, height: 3 }
만약 이후에 임의로 Square.prototype.width(또는 height)에 값을 부여하고 sq.width(또는 heigth)의 값을 지워버린다면 프로토타입 체이닝에 의해 엉뚱한 결과가 나오게 될 것이다.
나아가 constructor가 여전히 Rectangle을 바라보고 있다는 문제도 있다.
sq.constructor로 접근하는 프로토타입 체이닝을 따라 sq.__proto__.__proto__, 즉 Rectangle.prototype에서 찾게 되며, 이는 Rectangle을 가리키고 있기 때문이다.