자바스크립트는 프로토 타입 기반 언어라서 '상속'개념이 존재하지 않지만, ES6 이후 클래스 문법이 추가되고, 클래스 문법에서도 일정 부분은 프로토타입을 활용하고 있습니다.
class라는 의미는 '계급, 집단, 집합'등의 의미로 번역됩니다. 프로그래밍 언어적으로도 동일한 개념으로 접근하면 됩니다.
클래스(class)는 어떤 사물의 공통 특성을 모아 정의한 추상적인 개념입니다. 상위 클래스(SuperClass )와 하위 클래스(SubClass)로 나뉠 수 있습니다
인스턴스(instance)는 특정 클래스의 속성을 지니는 실존하는 사례입니다.
클래스는 하위로 갈수록 상위 클래스의 속성을 상속하면서 구체적인 요건이 추가되거나 변경됩니다.
하나의 인스턴스는 하나의 클래스만을 바탕으로 만들어집니다.
예시와 같이 알아보겠습니다.
// 생성자
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());
console.log(rect1.isRectangle());// Error: rect1.isRectangle is not a function
console.log(Rectangle.isRectangle(rect1));// true
getArea
는 rect1.__proto__.getArea
에 접근하는데, __proto__
가 생략했으므로, this가 rect1채로 실행되어 해당 메서드의 값이 반환됩니다. 이처럼 인스턴스에 직접 호출할 수 있는 메서드가 프로토타입 메서드라고 합니다.isRectangle
메서드가 있는지 검색했는데 없고, rect1.__proto__
에도 없으며, Object.prototype
에도 없는 걸 알고, 함수가 아니어서 실행할 수 없다는 에러가 발생합니다.이해 후 정리...🙌
var ES5 = function (name) {
this.name = name;
};
ES5.staticMethod = function() {
return this.name + ' staticMethod';
};
ES5.prototype.method = function() {
return this.name + ' method';
};
var es5Instance = new ES5('es5');
console.log(ES5.staticMethod); // ES5 staticMethod
console.log(es5Instance.method); // es5 method
var ES6 = class {
constructor (name) {
this.name = name;
}
static staticMethod () {
return this.name + ' staticMethod';
}
method () {
return this.name + ' method';
}
}
var es6Instance = new ES6('es6');
console.log(ES6.staticMethod()); // ES6 staticMethod console.log(rect1.getArea()); // 12
console.log(rect1.isRectangle()); // Error: rect1.isRectangle is not a function
console.log(Rectangle.isRectangle(rect1)); // true
console.log(es6Instance.method()); // es6 method
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: ', super.getArea());
}
}