클래스와 인스턴스

katsukichi·2021년 2월 25일
0

CodeStates_IM

목록 보기
10/48

객체지향 JavaScript

Object Oriented JavaScript

객체지향 ?

하나의 모델이 되는 청사진(blueprint)를 만들고 => class

그 청사진을 바탕으로 한 객체(object)를 만드는 프로그래밍 패턴 => instance

class 선언?

//ES5 문법
function Car(brand,name,color){
	//인스턴스가 만들어질때 실행되는 코드
}
//ES6 문법
class Car{
  constructor(brand,name,color){
    //인스턴스가 만들어질때 실행되는 코드
  }
}

최근에는 ES6문법을 주로 사용합니다.

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

클래스 : 속성의 정의

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

클래스 : 메소드의 정의

//ES5
function Car(brand,name,color){
  Car.prototype.refuel = function(){
    //연료 공급을 구현하는 코드
  }
  Car.prototype.drive = function(){
    //운전을 구현하는 코드
  }
}
//ES6
class Car{
  constructor(brand,name,color){
  }
  refuel(){
  }
  drive(){
  }
}

Prototype? constructor? this?

prototype : 모델의 청사진을 만들 때 쓰는 원형 객체(original form)입니다.

constructor : 인스턴스가 초기화 될때 실행하는 생성자 함수

this : 함수가 실행될 때, 해당 scope마다 생성되는 고유한 실행 context(execution context) new 키워드로 인스턴스를 생성했을때에는, 해당 인스턴스가 바로 this의 값이 됨

mdn메소드 설명을 보면

prototype 이라고 붙어있는경우가 많다.

Array.prototype.push() 이런경우가많은데

(push, filter, forEach ... 등등)

모두 원형객체에서 정의되어 있기 때문입니다.

profile
front-back / end developer / Let's be an adaptable person

0개의 댓글