React
리액트 ES6 문법 - 클래스
solfa
2024. 1. 28. 06:27
아래 책을 읽고 정리한 내용입니다.
https://m.yes24.com/Goods/Detail/87631428
클래스
⇒ 기존 자바스크립트 문법은 클래스 표현식이 없어서 prototype으로 클래스를 표현함
기본 자바스크립트의 클래스 표현 방법 알아보기
// ES5 문법
function Shape(x, y) {
this.name = 'Shape';
this.move(x, y);
}
// static 타입 선언 예제
Shape.create = function(x, y) {
return new Shape(x, y);
};
Shape.prototype.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);
var s2 = Shape.create(0, 0);
s.area(); // 0 -> 클래스의 상속으로 참조 가능한 거!!
function Circle(x, y, radius) {
Shape.call(this, x, y); -> super()느낌
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
- 기존은 함수를 생성자(construct)형태로 선언한 다음 상속이 필요한 변수나 함수를 prototype 객체에 할당하는 방법을 사용함!
- 프로토타입의 이해 → https://www.nextree.co.kr/p7323/
- prototype 객체는 new 연산자로 생성되는 객체 안에서 this 연산자의 함수 및 변수 선언 위치를 참조할 수 있는 요소, 이 특징을 이용함
- Shape.call(this, x, y); → super() 느낌
- Object.assign(Circle.prototype, Shape.prototype, { → 부모 클래스 함수를 상속하는 방법
- Circle.prototype 이걸 부모 클래스로 인식하고 덮어 씌우는!
ES6의 클래스 사용 방법 알아보기
// ES6 예제
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;
}
}
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(); // 100
- name = 'Shape'; → 클래스 변수를 선언하는 것과 동일한 작업을 수행!
- 클래스 정의 표현식에는 객체가 생성될 때 함께 만들어질 변수나 클래스 변수를 클래스 선언 블록 안에! 같이 정의할 수 있게 변경됨
- 생성자, 클래스 변수, 클래스 함수 정의에는 var, let, const를 사용하지 않음!
- extends 키워드로 클래스 상속도 가능!
- Java와 다른점은 다중 상속이나 인터페이스는 지원하지 않는다는 점!
728x90