클래스와 인스턴스

hyo·2022년 7월 24일
0

[Javascript] 기초 학습

목록 보기
58/62

객체 지향 프로그래밍

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

여기서 하나의 모델이 되는 청사진을 -> class
청사진을 바탕으로 한 객체 -> instance


class

우선 class를 만드는 두가지 방법이있다.

1. ES6가 도입되기 이전에 사용하던 함수를 사용하던 방식

->

// 함수를 사용한 방식
function Car(name, brand, price) {
  this.name = name;
  this.brand = brand;
  this.price = price;
}
Car.prototype.refuel = function() {
  
}

2. ES6 이후에 생긴 클래스 생성자를 이용한 방식

->

// 클래스 생성자를 이용한 방식
class Car{
  constructor(name,brand,price){
    this.name = name;
    this.brand = brand;
    this.price = price;
  }
  refuel() {
    
  }
}

정리해보면 청사진(blueprint)함수이고 class 이다.
constructor인스턴스가 초기화될 때 실행하는생성자 함수이다.


instance

위의 클래스 생성자를 이용한 방식을 사용한 클래스를 보면

class Car{
  constructor(name,brand,price){
    this.name = name;
    this.brand = brand;
    this.price = price;
  }
  refuel() {
    
  }
}
// class 를 바탕으로 한 객체는 -> instance
let user1Car = new Car('sportage','KIA','4000만원')

//  user1Car = {name: 'sportage', brand: 'KIA', price: '4000만원'}

user1Carinstance 이다.
this 키워드가 등장하는데 this인스턴스 객체를 의미한다.

profile
개발 재밌다

0개의 댓글