class
키워드를 이용해서 클래스를 선언할 수 있다.
class Person {
name;
constructor(name) {
this.name = name;
}
introduceSelf() {
console.log(`Hi! I'm ${this.name}`);
}
}
위의 Person
클래스는 다음과 같다.
name
프로퍼티를 갖는다.name
프로퍼티를 초기화하기 위해 하나의 name
파라미터를 갖는다.introduceSelf()
메서드는 객체의 프로퍼티를 참조하기 위해 this
키워들 사용한다.클래스 정의부분에 name
프로퍼티가 하나 외로히 놓여있다.
사실 이 부분은 생략해도 상관없다.
어차피 constructor의 this.name = name
부분에서 name
프로퍼티를 만들기 때문이다.
그러나 프로퍼티들을 명시적으로 리스트화해놓는것이 더 읽기 좋은 코드이기 때문에 써놓는것을 권장한다.
프로퍼티를 볼 때 타입이 추측가능하도록 하기위해 name = ""
처럼 빈 값으로 초기화할 수도 있다.
constructor는 constructor
키워드를 사용해서 정의한다.
만약 초기화 작업이 필요없다면, constructor를 생략할 수 있다.
생략할 시, default constructor가 생성된다.
class Animal {
sleep() {
console.log('zzzzzzz');
}
}
const spot = new Animal();
spot.sleep(); // 'zzzzzzz'
Person
클래스를 상속받아 Professor
클래스를 정의해보자.
class Professor extends Person {
teaches;
constructor(name, teaches) {
super(name);
this.teaches = teaches;
}
introduceSelf() {
console.log(`My name is ${this.name}, and I will be your ${this.teaches} professor.`);
}
grade(paper) {
const grade = Math.floor(Math.random() * (5 - 1) + 1);
console.log(grade);
}
}
extend
키워드를 이용해서 해당 클래스를 상속받을 수 있다.
Professor
클래스는 teaches
라는 새로운 프로퍼티를 가지므로 constructor의 매개변수로 name
뿐 아니라 teaches
값도 전달받아 초기화하도록 한다.
Professor
클래스의 constructor가 제일 먼저 해야할 일은 super()
를 이용해, name
매개변수를 부모클래스의 constructor로 전달하여 호출하는 것이다.
왜냐하면 부모 클래스의 모든 것들을 상속받은 뒤에 자식 클래스에서 추가 및 수정을 해야 논리적 오류가 발생하지 않기 때문이다.
하위 클래스가 자신을 초기화를 해야 한다면, 먼저
super()
를 사용하여 슈퍼 클래스 생성자부터 호출해야 한다.
마지막으로, 자바스크립트에서는 캡슐화를 어떻게 구현하는지 알아보자.
class Student extends Person {
#year;
constructor(name, year) {
super(name);
this.#year = year;
}
introduceSelf() {
console.log(`Hi! I'm ${this.name}, and I'm in year ${this.#year}.`);
}
canStudyArchery() {
return this.#year > 1;
}
}
위의 클래스 정의에서 #year
는 private data property이다.
클래스 정의 내부에서 #year
를 사용할 수 있지만, 객체 외부의 코드에서 #year
에 접근하면 오류가 발생한다.
const summers = new Student('Summers', 2);
summers.introduceSelf(); // Hi! I'm Summers, and I'm in year 2.
summers.canStudyArchery(); // true
summers.#year; // SyntaxError
private data property 뿐만 아니라 private method도 정의할 수 있다.
private data property처럼 이름 앞에 #
을 붙여주면 된다.
이러한 private 메서드들은 객체 자신의 메서드에서만 호출될 수 있다.
class Example {
somePublicMethod() {
this.#somePrivateMethod();
}
#somePrivateMethod() {
console.log('You called me?');
}
}
const myExample = new Example();
myExample.somePublicMethod(); // 'You called me?'
myExample.#somePrivateMethod(); // SyntaxError
[참고] : MDN