본문 바로가기

💻 개발자/🔨 HTML, CSS, JS

[JS] 객체지향 JavaScript (feat. class & instance)

반응형

1. class와 instance

객체 지향 프로그래밍은 하나의 모델이 되는 청사진(BluePrint)을 만들고 그 청사진을 바탕으로 한 객체를 만드는 프로그래밍 패턴이다.

여기서 청사진을 class라 할 수 있고, 객체를 instance라고 할 수 있다. 정확히는 인스턴스 객체(instance object)다.

//ES6
class Car {
	constructor(brand, name, color) {
    this.brand = brand;
    this.name = name;
    this.colr = color;
    }
    drive() {
    	console.log(this.name + '이(가) 운전을 시작합니다'
    }
}

let stonic = new Car('kia', 'stonic', 'gray')
stonic.color; // 'gray'
stonic.drive(); // 'stonic이(가) 운전을 시작합니다'
prototype - 모델의 청사진을 만들 때 쓰는 원형 객체(original form)
constructor - 인스턴스가 초기화될 때 실행하는 생성자 함수
this - 함수가 실행될 때 해당 scope마다 생성되는 고유한 실행 context(execution context)
- new 키워드로 인스턴스를 생성했을 때에는 해당 인스턴스가 바로 this의 값이 됨

 

2. 객체 지향 프로그래밍(Object Oriented Programming)

절차적 언어

  • 초기의 프로그래밍 언어는 일반적으로 절차적 언어라고 부름(C, 포드란 등)
  • 절차적 언어는 순차적인 명령의 조합

객체 지향 언어

  • "클래스"라고 부르는 데이터 모델의 청사진을 사용해 코드 작성
  • 현대의 언어들은 대부분 객체 지향의 특징을 갖고 있음(Java, C++, C# 등)
  • JavaScript: 객체 지향으로 작성 가능!

OOP(Object Oriented Programming)

  • OOP는 프로그램 설계 철학
  • OOP의 모든 것은 "객체"로 그룹화됨
  • OOP의 4가지 주요 개념을 통해 재사용성 증가

클래스와 인스턴스

  • 클래스는 일종의 원형(original form)으로 객체를 생성하기 위한 아이디어나 청사진
  • 인스턴스는 클래스의 사례(instance object)
  • 클래스는 객체를 만들기 위한 생성자(constructor) 함수 포함

OOP Basic Concepts

  • Encapsulation (캡슐화) => Reduce complexity + increase reusability
  • Injeritance (상속 => Reduce complexity + isolate impact of changes
  • Abstraction (추상화) => Eliminate redundant code
  • Polymorphism (다형성) => Refactor ugly (if/else if) statements

 

3. 클래스와 프로토타입

4. 프로토타입 체인

Person이라는 클래스를 상속받은 Teacher 클래스를 코드로 작성하면 다음과 같다.

class Teacher extends Person {
  constructor(first, last, age, gender, interests, subject, grade) {
    super(first, last, age, gender, interests);

    // subject and grade are specific to Teacher
    this.subject = subject;
    this.grade = grade;
  }
}

extends를 통해 상속받을 클래스를 확정한다.

super에는 상속받은 부모 클래스의 constructor 요소를 넣어 불필요한 코드를 적지 않아도 된다.

반응형