- 자바스크립트는 프로토타입 기반 언어라서 ‘상속’ 개념이 존재하지 않음. → 클래스와 비슷하게 동작하게끔 흉내 내는 여러 기법들이 탄생
01 클래스와 인스턴스의 개념 이해
- 클래스: 인스턴스를 만드는 틀. 하위로 갈수록 상위 클래스의 속성을 상속하면서 더 구체적인 요건이 추가, 변경됨
- 인스턴스: 클래스의 속성을 지니는 실존하는 개체를 일컬어 인스턴스라고 함
02 자바스크립트의 클래스
- 프로토타입 기반 언어이기 때문에 클래스의 개념이 존재하지 않음.
- 프로토타입을 클래스 관점에서 접근해보면 비슷하게 해석할 수 있음
- 프로토타입 메서드 : 인스턴스에서 직접 호출할 수 있는 메서드
- 스태틱 메서드 : 인스턴스에서 직접 접근할 수 없는 메서드
var Rectangle = function (width, height){
this.width = width;
this.height = height;
}
//프로토타입 메서드
Rectangle.prototype.getArea = function () {
return this.width * this.height;
}
//스태틱 메서드
Rectangle.isRectangle = function (instance){
return instance instanceof Rectangle && instance.width > 0 && instance.height > 0;
}
var rect1 = new Rectangle(3,4);
console.log(rect1.getArea()); //12
console.log(rect1.isRectangle(rect1)); // Error
console.lolg(Rectangle.isRectangle(rect1)); // true
03 클래스 상속
- 기본 구현
- 클래스가 구체적인 데이터를 지니지 않게 해야 함
04 ES6의 클래스 및 클래스 상속
var Rectangle = class {
constructor (width, height) {
this.width = width;
this.height = height;
}
getArea(){
return this.width * this.height;
}
};
var Square class extends Rectangle {
constructor (width){
super(width, width);
}
getArea(){
console.log('size is : ",super.getArea());
}
}