기존 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는 다중 상속 및 인터페이스는 지원하지 않는다. |
'Programming > Javascript' 카테고리의 다른 글
[ES6] Enhanced object property (0) | 2021.10.07 |
---|---|
[ETC] 비동기처리 (Callback / Promise) (0) | 2021.10.07 |
[ES6] Arrow Function / Spread operator (0) | 2021.10.07 |
[ETC] Object, Class, Instance (0) | 2021.10.07 |
드림코딩 by 엘리. JavaScript 기초 강의(10) - JSON 개념 정리와 활용방법 및 유용한 사이트 공유 (0) | 2021.10.07 |