[JavaScript]클래스와 인스턴스

신보연·2023년 3월 15일
0

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

Class:

class를 만드는 문법은 ES6에서 도입, 'class' 키워드를 이용해서 생성하며 함수처럼 선언식, 표현식 모두 가능.
constructor 메서드는 class 로 생성된 객체를 생성하고 초기화하기 위한 특수한 메서드.
"constructor" 라는 이름을 가진 특수한 메서드는 클래스 안에 한 개만 존재할 수 있다.
this는 쉽게말해 인스턴스 객체를 의미,
this에 할당한다는 것은 만들어지는 인스턴스에 brand,name,color를 할당하겠다는 뜻.

class의 특징

  • 호이스팅 ❌ (반드시 정의한 뒤에 사용할 수 있음.)
  • class의 본문(body)은 strict mode에서 실행.
  • 생성자 함수는 return값을 만들지 않음.
class Car{
  constructor(brand,name,color){
    this.brand = brand;
    this.name = name;
    this.color = color;
  }
  drive(){
    console.log(this.name + '가 운전을 시작합니다')
  }
}

Instance:

new 연산자를 이용해 객체타입의 인스턴스를 생성.
즉시 생성자 함수가 실행되며,
변수에 클래스의 설계를 가진 새로운 객체, 즉 인스턴스가 할당.
각각의 인스턴스는 클래스의 고유한 속성과 메서드를 갖게 됨.

let avante =new Car('hyundai','avante','black');
avante.color // 'black'
avante.drive() // 'avante'가 운전을 시작합니다.

ES5 vs ES6

//ES5
function Car(brand, name, color){
	this.brand=brand;
	this.name=name;
  	this.color=color;
}
Car.prototoype.drive = function{}

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

0개의 댓글