본문 바로가기

Programming Languages/javascript

class

class는 객체를 찍어 내는 공장이라고 생각하면 된다.

원래 javascript에서는 class를 지원하지 않았다. 대신에 constructor를 통해 객체를 찍어 내고 있다가 class라는 문법을 도입하였다.

 

클래스 표현 방법

function calCul(name,first,second){

  this.name = name;
  
  this.first = first;
  
  this.second = second;
  
};

calCul.prototype.sum = function(){

  return `${this.name} : ` + (this.first + this.second);
  
};

let park = new calCul('park',10,20);

 

위 코드를 class 로 다시 정리해 보면

 

class calCul{

  constructor(name,first,second){ 
  
    this.name = name;
    this.first = first;
    this.second = second;
    
  }
  
  sum(){
  
    return `${this.name} : ` + (this.first + this.second);
    
  }
  
}

let park = new calCul('park',10,20);

 

로 정리해 볼 수 있다.

클래스 선언을 사용하면 특수한 constructor 메서드 이름을 사용하여 클래스 내부에 직접 생성자를 정의 할 수 있다.

클래스 메서드는 간결한 구문을 사용하기 때문에 function 키워드를 사용할 필요가 없다. 그리고 다른 메서드 이름에는 특별한 의미가 없으므로 원하는 만큼 메서드를 추가할 수 있다.

'Programming Languages > javascript' 카테고리의 다른 글

Callback  (0) 2020.01.15
super  (0) 2020.01.05
prototype  (0) 2020.01.03