javascript 객체지향

Bonnie Ryu·2020년 9월 24일
1

객체지향 (Object Oriented Programming)

JavaScript의 필수 개념인 객체지향에 대해 정리해보았다.

✔ 알아볼 부분
- Class 와 Object / 만드는 법
- Instance
- 객체지향 특성 (캡슐화, 상속, 다형성, 추상화)

🔷 클래스와 오브젝트의 차이점

클래스오브젝트
only template, 틀 역할만instance of a class, 클레스를 이용하여 새로운 인스턴스 생성
한 번만 선언created many times
no data indata in, 실제로 데이터를 만드는 것은 Object

인스턴스(instance) :
인스턴스화 되는 시점에서 호출되는 메서드,
컴퓨터 저장공간에서 할당된 실체

// 1-1 클레스 선언 
class Person {
 // constructor
 constructor(name, age) {
     // fields
     this.name = name;
     this.age = age;
 }
 // methods
 speak() {
     console.log(`${this.name}: hello!`);
 }
}

// 1-2 오브젝트 생성

const bonnie = new Person('bonnie',3);
console.log(bonnie.name); // bonnie
console.log(bonnie.age); // 3
bonnie.speak(); //bonnie: hello!

🔷 객체지향 특성 이해하기

◼ 캡슐화(Encapsulation) : 객체의 특정 부분을 은닉화하여 사용에 제한을 두는 기술

  • 재사용성 증가
    같은 객체를 계속 생성하지 않아도 되기 때문에 스크립트의 재사용성이 높아진다.

  • 가독성 증가

  • 은닉성

    클레스 안에서 내부적으로 보여지는 변수(private)와 밖에서도 보여지는 변수(public)으로 구분되어 private에 대해 밖에서 보는 것은 불가능하기때문에 유출될 걱정이 없다.

Getter and Setters

class User {
constructor(firstName, lastName, age){
  this.firstName = firstName;
  this.lastName = lastName;
  this.age = age;
}

get age() {
  returen this._age;
}
set age(value) {
  this._age = value < 0 ? 0 : value;
}
}
const user1 = new User('Steve', 'job',-1);
console.log(user1.age) // 0

◼ 상속(Inheritance) : 하나 이상의 클래스를 특별한 버전의 클래스로 생성하는 기술.
부모 클래스의 인스턴스를 자식 클래스에 할당함으로써 상속이 이루어진다.

  • extends 키워드 : 자식클레스에서 상속을 받는다는 의미로 기재
  • super 키워드 : 상속을 받고, 부모 클래스의 생성자(constructor)를 호출하고 싶을 때 기재

◼ 다형성(Polymorphism) : 하나의 클래스나 메서드가 다양한 방식으로 동작이 가능 한 것

◽ 필요한 함수만 재 정의(overriding)할 수 있다.

override : 자식 클레스가 부모 클레스 중 하나에 대해 이미 제공한 메소드를 특정한 형대로 구현하는 것을 제공하는 것.

class Shape {
 constructor(width, height, color){
     this.width = width;
     this.height = height;
     this.color = color;
 }
 draw() {
     console.log(`drawing ${this.color} color if`)
 }
 getArea() {
     return this.width * this.height;
 }
}
// 상속 시 `extends`키워드 사용
class Rectangle extends Shape{}
class Triangle extends Shape{
 // `super`키워드를 사용해서 부모클래스의 생성자를 호출한다.
 super.draw();
 // 다형성
// overriding
 draw() {
     console.log('🔺')
 }

 getArea() {
     return (this.width * this.height)/2;
 }
}

// 인스턴스 생성
const rectangle = new Rectangle(20, 20, 'blue');
rectangle.draw(); // drawing blue color of
console.log(rectangle.getArea()); // 400
const triangle = new Triangle(20, 20, 'red');
triangle.draw(); // drawing blue color of, 🔺- 다형성 특성 반영
console.log(triangle.getArea()); // 200 - 다형성 특성 반영

◼ 추상화(Abstraction) : 각 객체들을 공통적인 프로퍼티와 메소드를 추출하는 작업

  • 추상화 자격요건
    1. 선언 부분(필드가 비어있는 메서드)만을 설계.
    2. 각 객체들에 공통적으로 들어가는 특성이 포함되어야 한다.

    같은 속성끼리 구분하여 class로 묶어준다.

참고 :
https://www.youtube.com/watch?v=_DLhUBWsRtw&list=PLv2d7VI9OotTVOL4QmPfvJWPJvkmv6h-2&index=6
https://developer.mozilla.org/ko/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
https://webclub.tistory.com/137
https://medium.com/@viktor.kukurba/object-oriented-programming-in-javascript-1-abstraction-c47307c469d1

profile
Ryuwisdom

0개의 댓글