본문 바로가기
부트캠프교육중/JavaScript

클래스와 인스턴스 1

by 뭉지야 2023. 1. 13.
728x90

#객체 지향 프로그래밍

-하나의 모델이 되는 청사진(blueprint)를 만들고, 그 청사진을 바탕으로 한 객체를 만드는 프로그래밍 패턴이다.

-청사진은 설계도

-설계도를 바탕으로 각각의 객체가 특정한 자동차 모델로 나오는 것

-현실세계를 기반으로 프로그래밍 모델을 만들때에 유용!


#클래스(class)

-청사진(ex. Car)

-대문자로 시작하며 일반명사로 만든다.(일반적인 함수는 적절한 동사를 포함하고 소문자로 시작.)

-> function Car(color){}

 

#인스턴스 객체(instance object)=인스턴스(instance)

- 청사진을 바탕으로 한 객체 (ex. 아반테, 미니)

-클래스의 설계를 가진 새로운 객체

-각각의 인스턴스는 클래스의 고유한 속성과 메서드를 가지게 된다.

-new 키워드를 사용.

-> let avante = new Car('blue')

 

#생성자(constructor) 함수

-인스턴스가 만들어질때 실행되는 코드

-생성자 함수는 return값을 만들지 않는다.

-클래스 내에서 생성자 함수는 하나만 쓸수있다.

-인스턴스 객체를 생성하고 초기화하는 특별한 메서드이다.

-생성자 함수를 작성하지 않으면 기본 생성자가 제공된다.

-부모클래스가 있고, 자식 클래스가 생성자 함수를 작성하지 않았다면 부모 생성자를 부른다.

- ES5: function Car(brand, name, color) {}

ES6: class Car { constructor(brand, name, color){}}


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

생성자 함수가 실행되면, 변수에 클래스의 설계를 가진 새로운 객체, 즉 인스턴스가 할당된다.

각각의 인스턴스는 클래스의 고유한 속성과 메서드를 가지게 된다.

(ex.아반테는 car의 고유한 속성과 메서드를 가진다)


<속성과 메서드>

클래스에 속성과 메서드를 정의하고, 인스턴스에서 이용한다.

속성: 브랜드, 차이름, 색상, 현재 연료상태, 최고 속력 등

메서드: 연료주입, 속력 설정, 운전 등

 

<속성>

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

여기서 this는 인스턴스 객체를 의미.

parameter로 넘어온 브랜드, 이름, 색상 등은 인스턴스 생성시 지정하는 값이다.

this에 할당한다는 것은 만들어진 인스턴스에 해당 브랜드, 이름, 색상을 부여하겠다는 의미이다.

 

<메서드> : 객체에 딸린 함수

ES5

function Car(brand, name, color) {생략}
Car.prototype.refuel = function() {
//연료 공급을 구현하는 코드
}
Car.prototype.drive = function() {
//운전을 구현하는 코드
}

ES6
class Car {
constructor(brand, name, color) {생략}
refuel(){
}
drive(){
}
}

-ES5에서는 prototype사용.

-ES6에서는 constructor사용.


#prototype

-모델의 청사진을 만들때 쓰는 원형객체(original form)이다.

 

#constructor

-인스턴스가 초기화될때 실행하는 생성자 함수

 

#this

-함수가 실행될때, 해당 scope마다 생성되는 고유한실행 context(execution context)

new키워드로 인스턴스를 생성했을 때에는, 해당 인스턴스가 바로 this의 값이됨


ES5

function Car(brand, name, color) {
this.brand = brand;
this.name = name;
this.color = color;
}
Car.prototype.drive = function(){
console.log(this.name + '가 운전을 시작합니다');
}
let avante = new Car('hyundai', 'avante', 'black');

avante.drive();   // 'avante가 운전을 시작합니다'
ES6

class Car{
construction(brand, name, color) {
this.brand = brand;
this.name = name;
this.color = color;

drive() {
console.log(this.name + '가 운전을 시작합니다');
}
}
let avante = new Car('hyundai', 'avante', 'black');

avante.drive();   // 'avante가 운전을 시작합니다'

<배열에서 적용>

let arr = ['code', 'states', 'pre'];

->

let arr = new Array('code', 'states', 'pre');

 

728x90

'부트캠프교육중 > JavaScript' 카테고리의 다른 글

프로토타입 (Prototype)  (0) 2023.01.13
객체 지향 프로그래밍  (0) 2023.01.13
메서드 호출  (0) 2023.01.13
[JavaScript] default parameter  (0) 2023.01.04
[JavaScript] 화살표함수  (0) 2023.01.04