자바스크립트도 절차적인 언어이다 따라서 함수가 중요한 역할을 하고 있다
프로그램 안에서 각각의 작은 기능을 수행하는 것
하나의 함수는 한 가지의 일만 하도록 만들어야 한다
자바스크립트에서 함수는 object이다.
연관있는 데이터를 한 곳에 묶어놓는 컨테이너 같은 존재
fields(속성)와 methods(행동)가 들어있다
틀만 정의
class Person{
//constructor
constructor(name, age){
//fields
this.name = name;
this.age = age;
}
//methods
speak(){
console.log(`${this.name}: hello!`);
}
}
const ellie = new Person('ellie', 20);
console.log(ellie.name); //ellie
console.log(ellie.age); //20
ellie.speak(); //ellie:hello!
class User{
constructor(firstName, lastName, age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
get age(){
return this._age;
}
//나이는 음수가 될 수 없다 따라서 setter로 나이를 0으로 만들어 줌.
set age(value){
this._age = value < 0 ? 0 : value;
}
}
const user1 = new User('Steve', 'Job', -1);
console.log(user1.age); //0
class Shape{
constructor(width, height, color){
this.width = width;
this.height = heigth;
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(); //부모의 draw도 호출하고 싶을 때
console.log('삼각형');
}
getArea(){
return (this.width * this.height) / 2;
}
}
const rectangle = new Rectangle(20, 20, 'blue'); //drawing blue color
const triangle = new Triangle(20, 20, 'red');
console.log(triangle.getArea()); //200
class를 이용해서 실제 데이터를 만드는 것