[JS] 객체 지향 프로그래밍

김태희·2023년 6월 6일
0

[HTML+CSS+JS] 시리즈

목록 보기
9/16
post-thumbnail

학습 참고자료 : 드림코딩 자바스크립트 기초 강의 (ES5+)

클래스(Class) : 붕어빵을 찍어낼 수 있는 틀과 같은 일종의 템플릿

객체(Object) : 클래스의 인스턴스(Instance)

1. 클래스의 선언

class Person{
  //생성자 선언 방법
  constructor(name, age){
    //필드 선언 방법
    this.name = name;
    this.age = age;
  }
  //메소드 선언 방법
  speak(){
    console.log(`${this.name}: hello!`);
  }
}
const taehui = new Person('tae hui', 20);
console.log(taehui.name);
taehui.speak();

생성자 선언 방법

  • constructor(매개변수){ this.필드명 = 매개변수 }

2. GetterSetter

객체 내부 속성에 직접 접근하지 않아 보안을 강화할 수 있고, 코드의 안전성과 유지보수성을 높일 수 있다는 장점이 있다

class User{
  constructor(firstName, lastName, age){
    this.firstName = firstName;
    this.lastName = lastName;
    this._age = age;
  }
  get age(){ //Getter 설정하는 방법
    return this._age; 
  }
  set age(value){ //Setter 설정하는 방법
    this._age = value; //변수 이름을 다르게 설정해야한다
  }
}
const taehui = new User('Kim', 'Tae', 20);
console.log(taehui);

Setter의 변수이름을 다르게 설정해야하는 이유 ?
값을 할당할때 setter 함수가 호출되게 된는데 setter 함수 내에서 변수이름이 같다면
자기 자신에 값을 할당하게되기에 오류가 발생한다

3. **Fields (public, private) **

최신 기술이라 잘 사용하지 않는다 !

publicField = 2; //public
#privateField = 0; //private

4. Static properties and methods

스태틱 메소드는 클래스에 연결되어 객체에 상관없이 사용할 수 있도록 한다

5. 상속

반복되어 사용 -> 상속을 이용 -> 유지 보수가 쉬워짐

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 width * this.height;
  }
}
class Rectangle extends Shape {
  draw() { //overriding 
    super.draw(); // 부모의 메소드를 재사용
    console.log('ㅎㅇ')
  }
}
class Triangle extends Shape {}

const rectangle = new Rectangle(20, 20, 'blue');
rectangle.draw();

overriding : 부모의 메소드를 재선언

6. class checking : instanceOf

rectangle instanceof Rectangle -> true
rectangle instanceof Shape -> true
rectangle instanceof Object -> true (모든 객체는 Object의 instance)

0개의 댓글