class 는 쉽게 template 이다.
class를 만들고 선언하는방법은 아래와같다.
class Person{
//constructor (class를 선언하고)
constructor(name, age){
//fields(안에 오브텍트를 만들고)
this.name = name;
this.age = age;
}
//methods 매소드를 생성
speak(){
console.log(`${this.name}: hello!`);
}
}
const jin = new Person("jin", 99);
console.log(jin.name);
console.log(jin.age);
jin.speak();
조금 복잡하다. 하지만 유용하고 좋다.
getter and setter 이건 클래스를 사용하는 사용자가 잘못사용할때 보완해주는것인다.
get 과 set을 설정하면 되는데
class User{
constructor(firstName, secondName, age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
get age(){
return this._age;
// 변수 이름을 다르게 하는이유는 this.age가 get을 호출하고
}
set age(){
if(value < 0) {
alert("age가 0 보다 적을수없습니다.")
}
this._age = value;
// 이름을 다르게 하는이유는 age가 set을 호출한다. 따라서 이름을 다르게 해 야한다.
}
}
const user = new User('jin', 'park', -1);
console.log(user.age);
age가 0보다 적게 적었을때 경고창이 나오게된다.
쉽게 class (클래스명) extends (클래스명) {}만써주면된다.
필요한 함수만 재정리해서도 쓸수있다(Triangle)
class Shape{
constuctor(width, height, color){
this.width = width;
this.height = height;
this.color = color;
}
draw(){
console.log(`drawing ${this.color} color of`);
}
getArea(){
return width * this.height;
}
}
class Rectangle extends Shape {}
class Triangle extends Shape{
getArea(){
super.draw();
// super. 을 쓰게될경우 부모의 것도 받을수있다
// console.log(`drawing ${this.color} color of`);
console.log("신기하네");
}
getArea(){
return(this.width * this.height) / 2;
}
}
const rectangle = new Rectangle(20, 20, 'blue');
rectangle.draw();
결과는 drawing blue color of라 나온다.