* class - 데이터를 넣지 않고 정의만함, 메모리 차지x, 틀 (es6에 추가)
class는 연관 있는 데이터를 한데 묶어놓는 컨테이너 역할을 함.
class 내부에는 속성(field),행동(method)이 들어갈 수 있음.
속성만 있는 경우도에는 data class 라고 함.
-template
-declare once
-no data in
class person{
name; //속성(field),
age; //속성(field),
speak(); //행동(method)
}
*object - 실제로 class(template)에 데이터를 넣어서 만드는것, 메모리 차지o, 내용이 들어간 틀
-instance of a class
-created many times
-data in
- 한마디로 class는 템플릿이며, object는 class를 사용해서 만드는 instance 이다. (class는 prototype 베이스이다.)
'use strict';
//사용법
//1. class 선언
class Person{
//constructor
constructor(name,age){
//fields
this.name = '홍길동';
this.age = 18;
}
//methods
speak(){
console.log(`${this.name}: hello!`);
}
}
class 안의 this는 class를 가리키며, super은 부모 class를 가리킨다. 위의 예제에서 super은 없지만, this가 가리키는 것은 Person이며, speak() method의 결과 값은 consloe.log('홍길동 : hello!'); 이다.
위의 class를 사용하는 예시는 아래와 같다.
const hwan = new person('hwan',30);
console.log(hwan.name); //hwan
console.log(hwan.age); //30
hwan.speak(); //hwan: hello!
* Getter and Setter
class User{
constructor(firstName,lastName,age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
}
const user1 = new User('Steve','Job',-1);
console.log(user1.age);
위의 스크립트는 user1.age를 -1로 반환한다. 하지만 age는 음수여서는 안된다. 사용자가 잘못 입력했을때를 대비해서 음수를 입력 했을때는 0으로 반환하게 해야한다. 그럴때 get과 set을 사용한다.
class User{
constructor(firstName,lastName,age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
get age(){
return this._age;
}
set age(value){
this._age = value < 0 ? 0 : value;
}
}
const user1 = new User('Steve','Job',-1);
console.log(user1.age); //0
get age()는 constructor()의 this.age = age에서 this.age를 가리키게되고, set age()는 this.age = age에서 age를 가리키게 된다.
이렇게 하면 class User에는 firstName, lastName, _age 총 3개의 필드가 있게된다.
new User에서 class에 값이 할당 될때, set age(value)에 할당되며 set age가 무한히 반복되게 되기 때문에 _age로 구분해준다. 그렇게 되면 class에 값이 할당 될때 _age에 할당되고 this.age = age에서 age에 입력된 값이 할당된다.
- 한 마디로 class에 값이 할당되면 get age()에서 계산되어져서 0이 age필드의 값으로 할당된다는 것이다.
*publicField 와 privateField
//생성자를 쓰지 않고 필드를 정의할 수 있다.
class Experiment{
publicField = 2; //그냥 정의 하면 public으로 외부에서 접근이 가능하다.
#privateField = 0; // #를 붙이면 private으로 내부에서만 접근이 가능하다.
}
const experiment = new Experiment();
console.log(experiment.publicField); //2
console.log(experiment.privateField); //undefined
*static
class Article{
static publisher = 'I love it';
constructor(Number){
this.Number = Number;
}
static printPublisher(){
console.log(this.publisher);
}
}
const article1 = new Article(1);
console.log(article1.publisher);//undefined
console.log(Article.publisher);//I love it
Article.printPublisher(); //I love it
object의 값에 따라 변하는것이 아니라 class안에 있는 고유의 값을 반복해서 출력해야 할때, static을 붙이면 된다.
object에 따라 달라지는 값이 아니기 때문에, article1에서 publisher은 찾을 수 없지만, class Artcle 자체에서 찾는다면 찾을 수 있다.
* 상속&다양성
class Shape{
constructor(width,height,color){
this.width = width;
this.height = height;
this.color = color;
}
draw(){
console.log(`drawing ${this.color} color of`);
}
getArea(){
return this.width * this.height;
}
}
class Rectangle extends Shape{}
class Triangle extends Shape{
draw(){
super.draw();
console.log('realdraw');
}
getArea(){
return (this.width * this.height) / 2;
}
}
const rectangle = new Rectangle(20,20,'blue');
const triangle = new Triangle(20,20,'red');
rectangle.draw();// drawing blue color of
console.log(rectangle.getArea());//400
triangle.draw();// drawing red color of //realdraw
console.log(triangle.getArea());//200
위의 내용은 이렇다.
1. class Shape 을 선언한다.
2. class Rectangle, class Triangle을 선언한다.
3. 2에서 선언한 class 각각에 Shape을 extends로 연결해준다.
4. class Rectangle, class Triangle 에 Shape의 필드와 메소드가 상속된다.
5. Shape의 내용을 수정하면 Rectangle, Triangle 둘 다 적용된다.
6. Triangle의 내용만 수정하고 싶다면, class Triangle 내부에서 수정한다.(덮어씌워짐)
7. 부모 extends로 이어진 class값도 불러오고 싶다면, super 키워드로 불러올 수 있다.
- 한마디로, 하나의 class를 extends로 다양한 class에 값을 상속시켜 적용시킬 수 있으며, 내부에서 오버라이딩 시키며 다양하게 사용할 수도 있다.
* instanceof
console.log(rectangle instanceof Rectangle);//true
console.log(triangle instanceof Rectangle);//false
console.log(triangle instanceof Triangle);//true
console.log(triangle instanceof Shape);//true
console.log(triangle instanceof Object);//true
좌측의 object가 우측 class 의 instance 인지 확인한다.
'JAVASCRIPT' 카테고리의 다른 글
페이지 새로고침 시 GET 파라미터 제거 (0) | 2022.02.23 |
---|---|
새로고침 방지하기 (0) | 2022.02.23 |
input type='file' multiple 업로드 미리보기 (0) | 2022.02.02 |
parameters (0) | 2022.01.24 |
function (0) | 2022.01.24 |