[JS] class

Jin.Dev·2020년 12월 19일
0
post-thumbnail

1. class란?

  • 객체(object)를 잘 설계하기 위한 틀
  • 이 때 객체(object)는 특정로직을 갖고 있는 행동(method)와 변경 가능한 상태(멤버 변수)를 가진다.

ex)

let ray = {  
  name: 'Ray',  
  price: 2000000,   
  getName: function() {  
    return this.name;  
  },   
  getPrice: function() {  
    return this.price;  
  },   
  applyDiscount: function(discount) {  
    return this.price * discount;   
  } 
}
  • ray 라는 객체는 name, price, getName, getPrice, applyDiscount라는 총 5개의 프로퍼티를 갖고 있다.
  • 객체의 프로퍼티 값에는 함수도 넣을 수 있다.

1.1 함수 호출 하는 방법

만약 getPrice라는 함수를 호출하고 싶다면 아래와 같이 하면 된다.

const rayPriceByFunction = ray.getPrice();
console.log(rayPriceByFunction);
  • 객체 내부에서, 해당 객체의 프로퍼티에 접근하려면 "this"라는 키워드를 사용할 수 있다. 그래서 getPrice 메서드에서 this.price로 price키에 접근할 수 있고 2000000 이라는 값을 갖고 올 수 있다.

2. 생성자(Constructor)

class Car {
  constructor(name, price) {
  this.name = name;
  this.price = price;
    }
  }
  • Car는 class 이름
  • Car class의 instance를 생설할때마다 constructor메서드가 호출된다.
  • constructor() 메서드는 name,price 2개의 인자를 받는다.
  • constructor() 메서드에 this 키워드를 사용하였고 class의 실행범위에서 this는 해당 instance를 의미한다.
  • constructor()에서 인자로 넘어노는 name과 price를 사용해 Car instance의 name, price 프로퍼티에 값을 할당했다.
  • 클래스 내에서 name, price와 같이 변경 가능한 상태값이자 class 내의 컨텍스트에서 어느 곳에서나 사용할 수 있는 변수를 '멤버 변수'라고 한다.
  • 멤버 변수는 'this' 키워드로 접근한다.

0개의 댓글

관련 채용 정보