TIL 25. JavaScript - Class

박소윤·2020년 11월 22일
0

Javascript

목록 보기
17/25
post-thumbnail

# Class

객체지향 프로그래밍으로, 프로그램을 객체로 구성하여 객체들간에 서로 상호작용하도록 작성하는 class

ray객체 정의 - property : name , price , getName , getPrice , applyDiscount

let ray = {  
  name: 'Ray',  
  price: 2000000,   
  getName: function() {  
    return this.name;  
  },   
  getPrice: function() {  
    return this.price;  
  },   
  applyDiscount: function(discount) {  
    return this.price * discount;   
  } 
}

const rayPriceByFunction = ray.getPrice(); 
console.log('함수로 접근 => ' +rayPriceByFunction);  //'함수로 접근 => 2000000'

# 생성자(Constructor)

class고유 속성이 생성자에 할당됨
class는 새로운 인스턴스를 생성할때 마다 생성자 메소드 호출

class Car {
  // 인스턴스가 생성될 때마다 호출됨
  constructor(name, price) {
    // Car class의 멤버 변수
    // Car class내부 어디에서나 사용가능
    // this는 해당 인스턴스의 속성을 말함
    this.name = name;
    this.price = price;
  }
}

# 인스턴스(Instance)

class를 통해 생성된 객체

키워드 변수이름 = new 클래스이름(인자);

new를 선언해 클래스를 통해 객체를 생성한다는 의미

# 메서드(Methods) - 함수

객체의 동작을 설명하며, 객체가 프로퍼티값을 갖고 있는 것을 메서드라 명칭.

class Car {
  constructor(name, price) {
    this.name = name;
    this.price = price;
    this.department = "위워크 선릉2호점";
  }
  
  // 메서드
  applyDiscount(discount) {  
    return this.price * discount;   
  }

  // 메서드
  changeDepartment(departmentName) {
    this.department = departmentName;
  }
}
profile
흐르듯 그리는 Front-end

0개의 댓글

관련 채용 정보