JavaScript

[객체 지향 프로그래밍]class 와 instance

숨냥 2023. 3. 15. 11:44

객체 지향 프로그래밍을 사용할 때 class와 instance가 등장하게 된다.

 

❖ 클래스 (class)

클래스란, 객체를 만들기 위한 설계도이다. 연관 되어있는 변수(속성)와 메소드가 집합되어있다.

 

❖ 특징

  • 일반적인 다른 함수들과 구분하기 위해 첫 글자를 대문자로 시작한다 ex) Apple
  • 보통은 단순한 명사로 작성

 

❖ 문법

보통은 ES6 방법을 주로 사용한다.

//ES5 : 클래스를 함수로 정의 한다
function Student(name, age, gender){
}

//ES6 : class 키워드를 사용해서 정의 가능
class Student {constuctor(name, age, gender){
}

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

class Student {constuctor(name, age, gender){
// thrtjd : this에 할당한다는 것은 만들어진 인스턴스에 해당 브랜드, 이름, 색상을 부여하겠다는 의미
	this.name = name;
    this.age = age;
    this.gender = gender;
    }
// 메소드 : class 키워드 안쪽에 묶어서 정의
	study(){
    }
    eatLunch(){
    }
    sleep(){
    }
}

 

 

❖ 인스턴스 (instance)

설계도(class)를 통해 만들어진 구체적인 실체 이다. 이를 인스턴스 객체(instance object) 줄여서 인스턴스(instance)라고 한다.

 

❖ 문법

new 키워드를 통해 인스턴스를 만들 수 있다.

class에서 정의한 속성과 메서드를 인스턴스에서 사용한다.

let student1 = new Student(Alice, 17, female)
student1.name;  //Alice - 속성
student1.study();  //student1이 공부를 한다. - 메소드

let student2 = new Student(Josh, 19, male)
student2.age;  //19
student2.sleep();  //student2이 잠을 잔다.

 

❖ 생성자 함수(constructor)

 

인스턴스를 생성하고 클래스 필드를 초기화하기 위한 함수

class Student {
  // constructor 생성자
  constructor(name) {
    this.name = name;
  }
}
// 인스턴스 생성
const friend = new Student('Alice');
console.log(friend); // Student {name: 'Alice'}

constructor는 인스턴스의 생성과 동시에 클래스 필드의 생성과 초기화를 실행

constructor은 생략이 가능하지만, 클래스 필드를 초기화해야 한다면 constructor를 생략해서는 안된다.