클래스와 인스턴스

Minseo Choi·2023년 5월 11일
0

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

여기서의 청사진(blueprint) --> class
그 청사진의 객체(object) --> instance

ES5 VS ES6

function Car(brand, name, color) {
  // 인스턴스가 만들어질 때 실행되는 코드
} --> ES5 클래스는 함수로 정의할 수 있음.
class Car {
  constructor(brand, name, color) {
    // 인스턴스가 만들어질 때 실행되는 코드
  }
} --> ES6에서는 class라는 키워드를 사용해 정의 할 수 있음.
	  최근에는 ES6방법을 자주 사용함.

new 키워드를 통해 클래스의 인스턴스를 만들어낼 수 있음.

let avante = new Car('hyundai', 'avante', 'black')
// 각각의 인스턴스는 Car라는 클래스의 고유한 속성과, 메소드를 갖고있음.

this

function Car (brand, name, color){
  this.brand = brand;
  this.name = name;
  this.color = color;
}   // ES5
class Car {
  constructor(brand, name, color) {
    this.brand = brand;
    this.name = name;
    this.color = color;
  }
} // ES6

한마디로 this는 인스턴스 객체를 의미한다. 위와 같이 this에 할당 한다는 것은
만들어진 인스턴스에 해당 브랜드, 이름, 색상을 부여하겠단 의미이다.

prototype? constructor? this?

prototype모델의 청사진을 만들 때 쓰는 원형 객체
constructor인스턴스가 초기화될 때 실행하는 생성자 함수
this함수가 실행될 때, 해당 scope마다 생성되는 고유한 실행context, new 키워드로 인스턴스를 생성했을 때는 해당 인스턴스가 바로 this 값이 됨
profile
개발자 되기

0개의 댓글