OOP 1) 클래스와 인스턴스

Hover·2023년 3월 15일
0

Javascript

목록 보기
1/6

1. 객체 지향 프로그래밍 개요

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

객체 지향 프로그래밍에서의 객체는 두 종류의 정보를 담고 있다.

첫째로는 속성(attributes)고 둘째는 동작을 나타내는 메소드(method)를 담고있다.

2. 클래스와 인스턴스

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

청사진이 class가 되는 것이고 청사진을 통해 만들어진 객체가 instance가 된다.


이런 클래스에서
업로드중..
이런 인스턴스들이 나오는 것!

javascript에서 클래스를 만드는 방법은 클래스 생성자를 이용하면 된다.

es5의 방식과 es6의 방식으로 나뉘어진다.


//es5
function Car2(brand, color, name) {
  this.brand = brand;
  this.color = color;
  this.name = name;

  Car2.prototype.drive = function () {
    return `${this.name} drive`;
  };
  Car2.prototype.stop = function () {
    return `${this.color} stop`;
  };
}



//es6
class Car {
  // 속성
  constructor(brand, color, name) {
    this.brand = brand;
    this.color = color;
    this.name = name;
  }

  // 메소드
  drive() {
    return `${this.name} drive`;
  }
  stop() {
    return `${this.color} stop`;
  }
}

3. 생성자

인스턴스를 사용하고 싶을 때는 new키워드를 사용하면 된다.

let car1 = new Car("bmw", "red", "hello");
console.log(car1.brand);
console.log(car1.stop());
  • new : 빈 객체 생성
  • Car : 객체 클래스 정의
  • (param) : 객체 속성 내용 입력
  • car1 : 생성된 객체를 변수 car1에 할당
profile
프론트엔드 개발자 지망생입니다

0개의 댓글