class
, instance
등의 용어를 이해할 수 있다.new
키워드를 사용해 instance
를 생성할 수 있다.class
를 사용할 수 있다.prototype
을 이용해 클래스의 원형을 만드는 방법을 이해할 수 있다.class
와 instance
의 관계는, 청사진과 이를 바탕으로 제작한 객체 관계이다.
class
를 정의하는 방법은 다음과 같이 두 가지가 있다. 클래스 이름은 첫 문자를 대문자로 작성한다.
function
을 이용한 방법functoin 클래스이름(매개변수) {
this.속성 = 매개변수;
}
클래스이름.prototype.메서드이름 = function() {
...
}
class
키워드를 이용한 방법class 클래스이름 {
constructor(매개변수) {
this.속성 = 매개변수
}
메서드이름() {
...
}
}
인스턴스를 생성하는 방법은 동일하다. new
키워드를 사용한다.
let 인스턴스이름 = new 클래스이름(인수);
new
키워드를 작성하지 않으면, class
키워드를 이용한 방법에서는 에러가 발생하지만, function
을 이용한 방법에서는 에러가 발생하지 않는다. 하지만 함수 그 자체가 실행된 결과를 반환하기 때문에, return
이 없으므로 인스턴스이름
은 undefined
를 가지게 된다. new
키워드를 꼭 작성해야 한다.
person
이라는 class
를 작성하고 몇 개의 instance
를 생성해보면,
class Person {
constructor(name, height, weight) {
this.name = name;
this.height = height;
this.weight = weight;
}
sayHello() {
console.log(`Hello. I'm ${this.name}. Nice to meet you!`);
}
getBMI() {
return (this.weight / ((this.height / 100) ** 2)).toFixed(2);
}
printThis() {
console.log(this);
}
}
let carly = new Person('Carly', 156, 48);
carly.sayHello(); // Hello. I'm Carly. Nice to meet you!
console.log(`${carly.name}'s BMI: ${carly.getBMI()}`); // Carly's BMI: 19.72
carly.printThis(); // Person { name: 'Carly', height: 156, weight: 48 }
클래스에 정의된 속성과 메서드는 아래와 같다.
name
, height
, weight
sayHello()
, getBMI()
instance
를 생성한 후, dot notation
을 통해 정의한 속성과 메서드를 이용할 수 있다. this
는 해당 instance
를 가리킨다.
function
으로 클래스를 생성하면 prototype
을 이용해 메서드를 추가해야 한다.
function Person(name, height, weight) { ... }
Person.prototype.sayHello() {
...
}
Person.prototype.getBMI() {
...
}
결과는 위와 동일하다.