드림코딩 자바스크립트 기초 강의를 들으며 학습한 내용을 정리해보았다.
⭐️ 재생목록 바로가기
class: templete
object: instance of a class
💡 클래스는 붕어빵 틀과 같은 템플릿을 말함
데이터가 들어있지 않음
이 클래스에는 이런이런 데이터가 들어올 수 있다! 라고 선언
(선언은 한 번만)
class는 ES6부터 추가된 prototype에 기반한 syntatical suger(문법적 설탕) -> 편리한 사용을 위해 만들어짐
💡 class라는 틀을 통해서 만들어지는 붕어빵
(class라는 틀에 팥, 슈크림, 피자 등등 object 지정 가능)
class Person{
constructor(name, age){
this.name = name;
this.age = age;
}
speak(){
console.log(`${this.name}, hello!`)
}
}
const Jin = new Person('Jin',26);
console.log(Jin.name);//Jin
console.log(Jin.age);//26
Jin.speak();//Jin, hello!
클래스 내에 값을 설정(set)하거나 가져올 수 있다(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;
}
}//age에 마이너스값을 넣으면 0을 반환
const user1 = new User("kang","Chul",-2);
console.log(user1.age)//0
⭐️ get 과 set에 쓰이는 변수는 매개변수와 같은 이름으로 호출하면 무한대로 호출될 수 있으므로 이름을 다르게 줘야함. (age -> _age)
상속받은 class(부모 class)의 일부 메서드를 자식 메서드에서 재정의 가능
💡 만약 대체가 아니라 부모 class의 메서드와 함께 추가하고 싶다면?
-> super 생성자로 부모 class 메서드 호출해준다.
⬇️ Shape라는 공통된 속성을 가진 object(rectangle, triangle)를 생성해보자!
1) Shape class(부모 클래스)와 그를 상속 받은 Rectangle(자식 class)로 만든 rectangle 오브젝트
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 {}//상속
const rectangle = new Rectangle(20, 20, 'green');//rectangle 오브젝트 생성
rectangle.draw();//400
console.log(rectangle.getArea());//drawing green color of
2) 상속을 받은 자식 클래스(Triangle)에 ovrriding으로 변주를 준 triangle 오브젝트
class Triangle extends Shape {
getArea(){
return (this.width * this.height) / 2;//overriding( 넓이 * 높이 -> (넓이 * 높이) / 2)
}
draw(){
console.log('🔺');//overriding
super.draw();//부모 class 메서드도 호출
}
}
const triangle = new Triangle(10, 30, 'blue');//triangle 오브젝트 생성
console.log(triangle.getArea());//150
triangle.draw();//🔺 , drawing blue color of
console.log(rectangle instanceof Rectangle);//true
console.log(triangle instanceof Rectangle);//false
console.log(rectangle instanceof Shape);//true
console.log(triangle instanceof Object);//true(밑의 설명 참고)
⭐️ 생성된 모든 객체, 클래스들은 Object 의 상속을 받는다.
-> command 누르고 Object 클릭하면 Object가 정의된 부분 확인 가능