Programming/Javascript

[ES6] Class

i독 2021. 10. 13. 06:49

기존 JS Code에서는 Class 표현식이 없기에 constructor 대신에 함수를 이용하여 prototype 객체에 할당하였다.

prototype 객체는 new 연산자로 생성되는 객체 안에서 this 연산자의 함수 변수 선언 위치를 참조 있는 요소이다.

 

function Shape (x,y) {
  this.name = 'Shape';
  this.move(x,y);
}
//static 함수를 선언
Shape.create = function(x,y) { return new Shape(x,y); };
//Instance Func 선언
Shape.protype.move = function(x,y) {
  this.x = x; this.y = y;
}
Shape.prototype.area = function() {
 return 0;
}
//혹은
Shape.prototype = {
  move: function(x,y) { this.x = x; this.y = y; },
  area: function() { return 0; }
};
var s = new Shape(0,0);
s.area(); // 0
new Shape(0,0) 함수를 호출하여 this 객체 해당하는 변수 함수가 prototype 객체 선언된 변수와 함수를 함께 참조.


new 연산자로 Shape() 함수를 호출하여 인스턴스 s 생성.


prototype 안의 move() 함수 호출 가능. 또한 추가된 area 함수 또한 참조할 있다.


Class 상속은 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() 내장 함수 call 통하여 부모의 생성자를 호출하여 초기값을 받는다. (Java super()함수처럼 사용)


Object 내장 assign() 함수를 이용하여 객체를 복사한다.
마치 부모 클래스에서 자식 클래스를 생성하듯 사용한다.


또한 area() 함수를 덮어 오버라이딩 기능을 구현한다.

 

ES6에서부터 class 키워드를 이용하여 기존 Object-oriented-Programing 처럼 class 선언 있다.

class Shape {
  static create(x, y) {
    return new Shape(x, y);
  }
  name = 'Shape';


  constructor(x, y) {
    this.move(x, y);
  }
  move(x, y) {
    this.x = x;
    this.y = y;
  }
  area() {
    return 0;
  }
}
class 키워드를 사용하여 Shape 정의


클래스 정의 표현식에서 객체가 생성될 함께 만들어질 변수나 클래스 변수(static) 클래스 선언 블록안에 같이 정의 있게 되었다.


*생성자, 클래스 변수, 클래스 함수 정의에는 변수 선언을 위한 키워드를 사용하지 않는다.

ES7에서 부터는 Class 확장표현으로 constructor() 함수가 추가 되었으며, this.name = 'Shape' 클래스 변수를 선언하는 것과 동일한 작업을 수행한다.

var s = new Shape(0, 0);
var s1 = Shape.create(0, 0);
s.area(); // 0


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;
  }
}


var c = new Circle(0, 0, 10);
c.area(); // 10
extends 키워드를 사용하여 Shape 클래스 상속.


super() 사용하여 상위 클래스 함수 호출.


하지만 ES6 다중 상속 인터페이스는 지원하지 않는다.