JS class
class 생성자 함수
함수가 특정기능을 하는 로직을 묶을 때 사용하는 문법이라면, 연관있는 변수와 함수를 하나로 묶을 때 사용하는 문법
-> 객체 단위로 코드를 그룹화 할 수 있으며 코드를 재사용하기 위해서
* class 사용방법
Class Person {
//constructor
constructor(name, age){
//fields
this.name = name;
this.age = age;
}
//method
speak(){
console.log(`${this.name} : hello!`);
}
}
+fields: 이름, 나이같은 속성
method: 행동
* class 사용해서 object 만들기
const soyeong = new Person('soyeong', 27);
console.log(soyoeng.name); -> soyeong
console.log(soyoeng.age); -> 27
soyeong.speak(); -> soyoeng: hello!
* Getter & 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); -> -1 age가 -1 될 수 없음!!
따라서
get 함수로 값 return하고
set 함수로 값 설정 +대신 set은 값을 설정하기때문에 값을 받아와야함
class User{
constructor(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
get age(){
retrun this._age;
}
set age(value){
if(value <0){
throw Error('age can not be negative');
}
this._age = value;
}
}
* 상속 & 다양성
class Shape {
//fields
constructor(width, height, color){
this.width = width;
this.height = height;
this.color = color;
}
//method
draw(){
console.log(`drawing ${this.color} color of`);
}
getAra(){
return this.width * this.height;
}
}
class를 연장
class Rectangle extends Shape {} -> 이렇게만 작성해도 Shape class가 Ractangle에 포함됨
const rectangle = new Rectangle(20, 20, 'blue');
rectangle.draw(); ->drawing blue color of
class Triangle extends Shape {
getAra(){
return (this.width * this.height) / 2;
}
}
const triangle = new Triangle(20, 20, 'red');
triangle.draw(); -> drawing red color of
console.log(triangle.getArea()); -> 400
그러나! 삼각형 넓이 구하는 공식은 다른 도형 넓이구한는 공식이랑 다름
따라서 재정의해줘야함. 필요할땐 재정의 가능!
* instanceOf :
object 가 class의 instance인지 아닌지 확인해줌 true or false로 return 됨
cosole.log(object instanceOf Class);
console.log(rectangle instanceOf Rectangle); -> true
console.log(triangle instanceOf Rectangle); -> false
console.log(triangle instanceOf Triangle); -> true
console.log(triangle instanceOf Shape); -> true shape를 상속했기 때문에!
console.log(triangle instanceOf Object); -> true