클래스(Class)

Gunwoo Kim·2021년 5월 13일
0

JavaScript

목록 보기
11/17
post-thumbnail

클래스는 객체 지향 프로그래밍에서 특정 객체를 생성하기 위해 변수와 메소드를 정의하는 일종의 틀로, 객체를 정의하기 위한 상태(멤버 변수)와 메서드(함수)로 구성된다. [위키백과]

클래스(class)

: 자바스크립트에서 클래스는 객체와 형태가 비슷합니다.

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

클래스의 기본 형태는 아래와 같습니다.

class MyClass {
  // 여러 메서드를 정의할 수 있음
  constructor() { ... }
  method1() { ... }
  method2() { ... }
  method3() { ... }
  ...
}

생성자(Constructor)

객체와 클래스, 둘의 가장 큰 차이는 constructor 라는 생성자 함수입니다.

클래스 형태가 아래와 같을때 class로 객체를 생성하는 과정을 인스턴스화라고 부릅니다.

class Car {
  // 생성자
  constructor(name, price) {
    this.name = name; // 인스턴스
    this.price = price;
  }
  // 메서드
  getPrice: function() {  
    return this.price;  
  }
}

const ray = new Car('Ray', 2000000); // 인스턴스화

this.name, this.price 와 같은 변수를 멤버 변수 라고 합니다.

인스턴스(Instance)

: 인스턴스(Instance)class를 통해 생성된 객체입니다.
인스턴스는 classproperty이름과 method를 갖는 객체입니다.

메서드(Methods)

: 메서드함수입니다. 그런데 객체가 프로퍼티 값으로 갖고 있는 것을 메서드라고 부릅니다. Class의 method는 Object(객체)의 문법과 똑같습니다.

0개의 댓글