ES6에서 class라는 문법이 추가되었고, 기존의 prototype 기반으로 클래스를 선언하는 것보다 명료하게 클래스를 선언할 수 있게 되었다.
ES6 이전에는 자바스크립트에 클래스(class) 없었다.
기존에는 클래스를 구현하기 위해서 prototype을 사용하여 작업
클래스안에 메소드를 선언하기위해서 prototype 특수변수를 사용하여
각각의 메소드이름에 함수를 정의하는 방식으로 사용
function Shape (x,y) {
this.name = 'Shape';
this.move(x,y);
}
Shape.prototype.move = function(x,y) {
this.x = x;
this.y = y;
}
Shape.prototype.area = function() {
return 0;
}
var s = new Shape(0,0);
s.area(); //0
클래스의 상속은 prototype객체의 값을 객체내장함수를 사용해 덮어씌우는 방식 이용하였다.
function Circle(x,y,radius) {
shape.call(this,x,y);
this.name = 'Circle';
this.radius = radius;
}
Object.assign(Circle.prototype, Shape.prototype, {
area: function() {
return this.radius * this.radius;
}
});
var c = new Circle(0,0,10);
c.area(); // 100
Circle()함수의 자식 클래스를 생성한 것이다.
자식클래스 Circle은 내장함수 call()을 통해 부모의 생성자를 호출하여 초기값을 상속받고 추가하고자 하는 radius 변수를 선언하였다.
부모 클래스 함수를 상속하는 방법으로는 Object에 내장된 assign()함수를 이용하여 이 area()함수는 Shape.prototype에 정의된 area()함수를 덮어씌운다.
그리하여 area()의 결과값은 이후 덮어쓴 area()함수의 결과값인 100이 나온다.
class Shape {
name = 'shape'; //es7표현방법으로 var나 특정한 키워드없이 변수가 선언됨
constructor (x,y) {
this.move(x,y);
}
move(x,y) {
this.x = x;
this.y = y;
}
area() {
return 0;
}
}
var s = new Shape(0,0);
s.area();
코드를 보면 class키워드로 Shape 클래스를 정의했으며, Shape 클래스 안에 생성자(constructor)함수도 추가되었다.
객체가 생성될때 함께 만들어질 변수나, 클래스 변수를 정의할수 있다
class Circle extends Shape {
constructor(x,y, radius) {
super(x,y);
this.radius = radius;
}
area() {
if (this.radius ===0) return super.area();
return this.radius * this.radius;
}
}
Circle 클래스는 extends 키워드를 사용하여 Shape클래스를 상속한다.
Circle 클래스는 contructor에서 변수가 변화되기 때문에
contructor를 선언하게된다.
super함수는 부모의 생성자를 호출하고 radius라는 변수만 추가되었다.
상속을 하게되면 기존의 모든 메소드들이 상속이되고
추가적으로 덮어씌우고싶은 새 정의 함수만 정의하면 된다