본문 바로가기
프로그래밍/개발 언어

클래스와 인스턴스

by monicada 2022. 5. 25.
728x90

객체지향프로그래밍: 데이터와 기능을 한곳에 묶에서 처리 

- 하나의 청사진(blueprint)를 만들고 -> class

클래스에 속성과 메소드를 정의하고, 인스턴스에서 사용 

// 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;
  } 
}

- 청사진을 바탕으로 객체(object)를 만드는 -> instance

인스턴스를 만들 때 new키워드 사용 

let avante = new Car('hyundai', 'avante', 'black');

 

클로저를 이용해 매번 새로운 객체 생성하기 (클로저 모듈 패턴)

function makeCounter() {
    let value = 0;
    return {
        increase: function(){
            value++;
        }
        decrease: function() {
            value--;
        }
        getValue: function() {
            return value;
        }
    }
}

let counter1 = makeCounter()
counter1.increase()
counter1.getValue()

let counter2 = makeCounter()
counter2.decrease()
counter2.getValue()
prototype 모델의 청사진을 만들 때 사용하는 객체
constructor 인스턴스 초기회 실행하는 생성자 함수
this 함수 실행 시, 해당 scope마다 생성된느 고유한 실행 context

 

'프로그래밍 > 개발 언어' 카테고리의 다른 글

JSON.stringify  (0) 2022.06.24
프로토타입과 클래스  (0) 2022.05.25
고차함수 코플릿  (0) 2022.05.24
반복문  (0) 2022.05.18
문자열  (0) 2022.05.18

댓글