클래스는 2015년에 Javascript에 추가된 문법으로, 이전에는 함수로 객체를 만들었다.
function createMonster(name, hp, att, xp) {
return { name, hp, att, xp };
}
const monster1 = createMonster('슬라임', 25, 10, 11);
const monster2 = createMonster('슬라임', 26, 10, 10);
const monster2 = createMonster('슬라임', 25, 11, 10);
여기서 중요한 점은, 생성한 3개의 객체가 서로 참조 관계가 아닌, 다른 객체여야 한다는 점이다.
new를 붙여 호출하는 함수를 생성자 함수 라고 한다.
조금 더 클래스에 가까운 방식으로 객체를 생성하면 다음과 같다.
function Monster(name, hp, att, xp) {
this.name = name;
this.hp = hp;
this.att = att;
this.xp = xp;
}
const monster1 = new createMonster('슬라임', 25, 10, 11);
const monster2 = new createMonster('슬라임', 26, 10, 10);
const monster2 = new createMonster('슬라임', 25, 11, 10);
주의) new
를 붙이지 않고 호출하게 되면 this
는 window
가 되어, window.name
의 값을 바꾸게 되므로 반드시 new
를 붙여야 한다.
※ 생성자 함수의 이름은 보통 대문자로 시작한다.
Javascript는 생성자 함수를 조금 더 편하게 쓸 수 있도록 클래스 문법을 도입하였다.
class Monster {
constructor(name, hp, att, xp) {
this.name = name;
this.hp = hp;
this.att = att;
this.xp = xp;
}
}
const monster1 = new createMonster('슬라임', 25, 10, 11);
const monster2 = new createMonster('슬라임', 26, 10, 10);
const monster2 = new createMonster('슬라임', 25, 11, 10);
클래스에
new
를 붙여 호출하면constructor
함수가 실행되고, 객체가 반환된다. 여기서this
는 생성된 객체 자신을 가리키게 된다.
아래의 두 코드를 보자.
클래스 문법 (생성자) 사용
class Monster {
constructor(name, hp, att, xp) {
this.name = name;
this.hp = hp;
this.att = att;
this.xp = xp;
}
attack(monster) {
monster.hp -= this.att;
this.hp -= monster.att;
}
heal(monster) {
this.hp += 20;
this.hp -= monster.att;
}
}
공장 함수 사용
function createMonster(name, hp, att, xp) {
return {
name, hp, att, xp,
attack(monster) {
monster.hp -= this.att;
this.hp -= monster.att;
},
heal(monster) {
this.hp += 20;
this.hp -= monster.att;
},
};
}
둘이 비슷해 보이지만 한가지 큰 차이점이 있다.
공장 함수에서 객체를 생성할 때마다 attack과 heal 메서드도 새로 같이 생성된다는 점이다.
반면 클래스 문법에서는 한번 만든 attack과 heal 메서드는 계속 재사용한다.
생성자 함수 사용
function Monster(name, hp, att, xp) {
this.name = name;
this.hp = hp;
this.att = att;
this.xp = xp;
}
Monster.prototype.attack = function(monster) {
monster.hp -= this.att;
this.hp -= monster.att;
};
Monster.prototype.heal = function(monster) {
this.hp += 20;
this.hp -= monster.att;
};
생성자 함수에 메서드를 추가할 때에는 prototype이라는 속성 안에 추가해야 한다.
prototype 속성 안에 추가한 메서드를 프로토타입 메서드라고 한다.이렇게 하면 공장 함수와는 달리
attack
과heal
메서드를 재사용할 수 있다. (하지만 생성자 함수와 프로토타입 메서드가 하나로 묶여있질 않다)
결국, 이 모든 문제점을 해결(함수 재사용, 생성자 함수와 묶어서 보기 편하게 하기)한 것이 클래스 문법이다.