객체지향 프로그래밍이란 무엇일까? 객체지향 프로그래밍이란 프로그램을 객체들로 구성하고, 객체들 간에 서로 상호 작용하도록 작성하는 방법이다.
Class는 이 객체지향 프로그래밍의 핵심이라고 할 수 있다. Class와 Object는 어떤 관계가 있는지 한 번 알아보자!
class는 변수 field와 메소드를 가지고 있는 템플릿이다.
class로 만들어진 대상이다.
// 인스턴스 생성
const jisu = new Person('Jisu', 25);
// 인스턴스의 속성값 호출
console.log(jisu.name); // Jisu
console.log(jisu.age); // 25
// 인스턴스의 메소드 호출
jisu.speak(); // Ha, Ha, Ha!
const jisu = new Person('Jisu', 25);
위와 같이 클래스를 가지고 생성된 객체를 Instance라고 부른다.
class Person {
// constructor[생성자]
constructor(name, age) {
// fields
this.name = name;
this.age = age;
}
}
class Person
: Person
은 클래스의 이름. 항상 대문자로 시작. CamelCase로 작성constructor()
: Person
클래스의 인스턴스를 생성할 때마다 호출됨this
: 클래스에서 this
는 해당 instance를 의미this
키워드로 접근함클래스로 인스턴스를 생성했을 때 필드에 있는 속성들의 값을 정의하여 다양한 객체들을 만들 수 있다.
const jisu = new Person('Jisu', 25);
인스턴스는 클래스로 생성된 객체
클래스의 property 이름과 method를 갖는 객체이다.
인스턴스마다 다른 property 값을 가지고 있음
new
라는 키워드를 붙여서 생성
() 안에 필요한 정보를 인자로 클래스의 생성자에게 넘겨줌
class Person {
// constructor[생성자]
constructor(name, age) {
// fields
this.name = name;
this.age = age;
}
// methods
speak() {
console.log(`${this.name}: Ha, Ha, Ha!`);
}
}
class User {
constructor(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
get age() {
return this._age;
}
set age(value) {
this._age = value < 0 ? 0 : value;
}
}
const user1 = new User('Steve', 'Job', -1);
console.log(user1.age); // 0
User class로 user1이라는 인스턴스를 만들었다.
User의 속성값에는 성, 이름, 나이가 있는데 인스턴스에서 정의한 나이는 -1이다.
나이가 -1? 있을 수 없는 숫자다.
이러한 현상을 방지하기 위해서 getter와 setter가 필요한 것이다.
age에 값을 할당했을 때 생성자의 this.age = age;
코드로 찾아가게 된다.
this.age
에서 getter를 호출하고 = age;
에서 setter를 호출하게 되는데 만약 setter의 코드를
this.age = value < 0 ? 0 : value;
로 적는다면 무슨 일이 일어날까?
값을 업데이트하는 것이 아니라 setter의 함수 이름과 같아 반복해서 setter를 호출하기 때문에 스택이 꽉 찼다는 오류가 발생한다.
그래서 _를 넣어 변수를 약간 다르게 구별해주는 것이 필요하다.
this._age = value < 0 ? 0 : value;
class Shape {
constructor(width, height, color) {
this.width = width;
this.height = height;
this.color = color;
}
draw() {
console.log(`color : ${this.color}`);
}
getArea() {
return this.width * this.height;
}
}
class Rectangle extends Shape {}
class Triangle extends Shape {
draw() {
//공통적으로 정의한 메소드를 호출하고 싶을때 - super.메소드
super.draw();
console.log('🔺');
}
// overriding : 재정의
getArea() {
return (this.width * this.height) / 2;
}
}
const rectangle = new Rectangle(20, 20, 'yellow');
rectangle.draw();
console.log(rectangle.getArea());
const triangle = new Triangle(20, 20, 'gray');
triangle.draw();
console.log(triangle.getArea());
공통적인 클래스 Shape
를 정의하고 extends를 사용하여 클래스를 포함시킨 코드이다.
여러 클래스가 Shape를 기본으로 가지면서 다양한 방법으로 코드를 재정의할 수 있다. 이것을 오버라이딩(overriding)이라고 한다.