| 클래스 | 생성자 함수 |
|---|---|
| new 연산자 없이 호출하면 에러 발생 | new 연산자 없이 호출하면 일반 함수로서 호출 |
| 상속을 지원하는 extends와 super 키워드 제공 | 미제공 |
| 호이스팅이 발생하지 않는 것처럼 동작 | 함수 선언문으로 정의된 생성자 함수는 함수 호이스팅, 함수 표현식으로 정의한 생성자 함수는 변수 호이스팅 발생 |
| 암묵적으로 strict mode 지정되고 해제 불가능 | 암묵적으로 strict mode 지정되지 않음 |
| constructor, 프로토타입 메서드, 정적 메서드는 프로토타입 어트리뷰트 [[Enumerable]]이 false => 열거 불가능 | 열거 가능 |
// 클래스 선언문
class Person {}
// 익명 클래스 표현식
const Person = class {};
// 기명 클래스 표현식
const Person = class MyClass {};
const Person = '';
{
console.log(Person); // Cannot access 'Person' before initialization
class Person { }
}
const Person = class MyClass { };
const me = Person(); // TypeError: Class constructor MyClass cannot be invoked without 'new'
// new를 사용해야 한다
const me = new Person();
// MyClass라는 클래스 이름은 클래스 몸체 내부에서만 유효
console.log(MyClass); // MyClass is not defined
const you = new MyClass(); // MyClass is not defined
클래스의 constructor 메서드와 프로토타입의 constructor 프로퍼티
이름이 같아 혼동하기 쉽지만, 직접적인 관련은 없다. 프로토타입의 constructor프로퍼티는 모든 프로토타입이 가지고 있는 프로퍼티이며, 생성자 함수를 가리킨다.
constructor의 특징
- constructor라는 이름은 변경 불가능
- 클래스 내에 한 개만 존재 가능
- 생략 시, 빈 constructor가 암묵적으로 정의된다
- 암묵적으로 this를 반환한다 (따라서 return은 생략할 것)
- 클래스가 평가된 결과에 constructor는 존재하지 않는다. 생성된 함수 객체 자체가 constructor의 결과물이기 때문.
class Person {
constructor(name,address) {
// 인수로 인스턴스 초기화
this.name = name;
this.address = address;
// return {}; // 이렇게 객체를 반환하면 constructor의 기본 동작을 훼손하는것. return은 반드시 생략할 것.
}
}
// 인스턴스 프로퍼티가 추가된다.
const me = new Person('Lee','Seoul');
console.log(me); // Person { name: 'Lee', address:'Seoul' }
class Person {
// 생성자
constructor(name) {
// 인스턴스 생성 및 초기화
this.name = name;
}
// 프로토타입 메서드
sayHi() {
console.log(`Hi! My name is ${this.name}`);
}
}
const me = new Person('Lee');
me.sayHi(); // Hi! My name is Lee
// me 객체의 프로토타입은 Person.prototype이다.
Object.getPrototypeOf(me) === Person.prototype; // -> true
me instanceof Person; // -> true
// Person.prototype의 프로토타입은 Object.prototype이다.
Object.getPrototypeOf(Person.prototype) === Object.prototype; // -> true
me instanceof Object; // -> true
// me 객체의 constructor는 Person 클래스다.
me.constructor === Person; // -> true
class Person {
// 생성자
constructor(name) {
// 인스턴스 생성 및 초기화
this.name = name;
}
// 정적 메서드
static sayHi() { // static 키워드!
console.log('Hi!');
}
}
// 정적 메서드는 클래스로 호출한다.
// 정적 메서드는 인스턴스 없이도 호출할 수 있다.
Person.sayHi(); // Hi!
// 인스턴스 생성
const me = new Person('April');
me.sayHi(); // TypeError: me.sayHi is not a function
class Square {
// 정적 메서드
static area(width, height) {
return width * height;
}
}
console.log(Square.area(10, 10)) // 100
class Square {
constructor(width, height) {
this.width = width;
this.height = height;
}
// 프로토타입 메서드
area() {
return this.width * this.height;
}
}
const square = new Square(10, 10)
console.log(square.area()) // 100
class Person {
constructor(name) {
// 인스턴스 프로퍼티
this.name = name; // name 프로퍼티
}
}
const me = new Person('Lee');
// public하므로 그냥 불러올 수 있다.
console.log(me.name); // Lee
class Person{
constructor(firstName, lastName){
this.firstName = firstName;
this.lastName = lastName;
}
//fullName은 접근자 함수로 구성된 접근자 프로퍼티다.
//getter함수
get fullName(){
return `${this.firstName} ${this.lastName}`;
}
//setter 함수
set fullName(name){
[this.firstName, this.lastName] = name.split(' ');
}
}
const me = new Person('Ungmo','Lee');
console.log(`${this.firstName} ${this.lastName}`); //Ungmo Lee
me.fullName = 'Heegun Lee';
console.log(me); //{firstName : 'Heegun', lastName : 'Lee'}
console.log(me.fullName); // Heegun Lee
// 어차피 public인데 접근자 프로퍼티가 의미가 있나?
me.firstName = 'Ed'
console.log(me.fullName); // Ed Lee
class Person {
name = 'Lee';
}
const me = new Person();
console.log(me); // Person {name: "Lee"}
특징
1. 클래스 필드를 정의하는 경우 this에 클래스 필드를 바인딩하지 말 것(this는 constructor와 메서드 내에만 유효)
2. 클래스 필드를 참조하는 경우 반드시 this를 사용해야 한다.
3. 클래스 필드에 초기값을 할당하지 않으면 undefined를 갖는다.
4. 함수를 클래스 필드에 할당할 수 있다.(클래스필드를 통해 메서드를 정의할 수 있다.)
//1. this에 클래스 필드를 바인딩해서는 안된다.
class Person {
this.name = " "; //SyntaxError : Unexpected token '.'
}
// 2. 클래스 필드 참조 시, 반드시 this 사용
class Person {
name = 'Lee';
constructor() {
console.log(name); //ReferenceError : name is not defined
}
}
// 3. 클래스 필드를 초기화하지 않으면 undefined를 갖는다.
class Person{
name;
}
const me = new Person();
console.log(me); // Person{name : undefined}
// 4. 함수를 클래스 필드에 할당할 수 있다.
class Person{
//클래스 필드
name = 'Lee';
//클래스 필드에 함수를 할당
getName = function(){
return this.name;
}
//화살표 함수로 정의할 수도 있다.
//getName = () => this.name;
}
const me = new Person();
console.log(me); //Person{name : "Lee", getName: f}
console.log(me.getName()); //Lee
class Person{
// private 정의
#name = '';
constructor(name){
this.#name = name;
}
//name접근자 프로퍼티다.
get name(){
//private 필드를 참조하여 trim한 다음 반환한다.
return this.name.trim();
}
}
const me = new Person('Lee');
console.log(me.name); //Lee
| 접근 가능성 | public | private |
|---|---|---|
| 클래스 내부 | O | O |
| 자식 클래스 내부 | O | X |
| 클래스 인스턴스를 통한 접근 | O | X |
class MyMath{
//static public 필드 정의
static PI = 22/7;
//static private 필드 정의
static #num = 10;
//static 메서드
static increment(){
return ++MyMath.#num;
}
}
console.log(MyMath.PI); //3.142857142857143
console.log(MyMath.increment()); //11
class Animal{
constructor(age, weight){
this.age = age;
this.weight = weight;
}
eat() { return 'eat'; }
move() { return 'move'; }
}
//상속을 통해 Animal클래스를 확장한 Bird 클래스
class Bird extends Animal { // extends 키워드 사용
fly() { return 'fly';}
}
const bird = new Bird(1,5);
console.log(bird); // Bird{age : 1, weight : 5}
console.log(bird instanceof Bird); // true;
console.log(bird instanceof Animal); // true;
console.log(bird.eat()); // eat
console.log(bird.move()); // move
console.log(bird.fly()); // fly

//수퍼(베이스/부모)클래스
class Base{}
//서브(파생/자식)클래스
class Derived extends Base{}
extends의 역할
- 수퍼클래스와 서브클래스 간의 상속 관계를 정의
- 클래스 간의 프로토타입 체인 생성(프로토타입 메서드, 정적 메서드 모두 상속 가능)
//생성자 함수
function Base(a){
this.a = a;
}
//생성자 함수를 상속받는 서브 클래스
class Derived extends Base{}
const derived = new Derived(1);
console.log(derived); //Derived{a:1}
fucntion Base1{}
class Base2{}
let condition = true;
//조건에 따라 동적으로 상속 대상을 결정하는 서브 클래스
class Derived extends (condition ? Base1 : Base2) {}
const derived = new Derived();
console.log(derived); //Derived {}
console.log(derived instanceof Base1); // true
console.log(derived instanceof Base2); // false
class Base {}
class Derived extends Base {}
class Base {
constructor() {}
}
class Derived extends Base {
constructor(...args) { super(...args); }
}
const derived = new Derived();
console.log(derived); // Derived {}
super의 동작
- 호출 : super 클래스의 constructor를 호출한다.
- 참조 : super클래스의 메서드를 호출할 수 있다.
// 수퍼클래스
class Base{
constructor(a,b) {
this.a = a;
this.b = b;
}
}
//서브클래스
class Derived extends Base{
//다음과 같이 암묵적으로 constructor가 정의된다.
// constructor(...args) { super(...args); }
// 따라서 다음과 같은 생성자가 정의된다
// constructor(a,b)
// super(a,b);
// this.c = c;
//}
}
const derived = new Dervied(1,2,3);
console.log(derived); // Derived {a: 1, b: 2, c: 3}
super 호출 시 주의 사항
1. 서브클래스에서 constructor를 생략하지 않은 경우, 서브클래스의 constructor에서는 반드시 super를 호출해야 한다.
2. 서브클래스의 constructor에서 super를 호출하기 전에는 this를 참조할 수 없다.
3. super는 반드시 서브클래스의 constructor에만 호출한다. 서브 클래스가 아닌 클래스의 constructor나 함수에서 super를 호출하면 에러가 발생한다.
//수퍼클래스
class Base {
construcotor(name) {
this.name = name;
}
sayHi() {
return `Hi! ${this.name}`;
}
}
//서브클래스
class Derived extends Base {
sayHi(){
//super.sayHi는 수퍼클래스의 프로토타입 메서드를 가르킨다.
return `${super.sayHi()}. how are you doing?`;
}
}
const derived = new Derived('Lee');
console.log(derived.sayHi()); //Hi! Lee. how are you doing?
//수퍼클래스
class Base {
static sayHi() {
return 'Hi';
}
}
//서브클래스
class Derived extends Base {
static sayHi(){
//super.sayHi는 수퍼클래스의 정적 메서드를 가리킨다.
return `${super.sayHi()} how are you doing?`;
}
}
console.log(Derived.sayHi()); //Hi! how are you doing?
인스턴스 생성 과정
1. 서브클래스의 super호출
2. 수퍼클래스의 인스턴스 생성과 this바인딩
3. 수퍼클래스의 인스턴스 초기화
4. 서브클래스 constructor로의 복귀와 this바인딩
5. 서브클래스의 인스턴스 초기화
6. 인스턴스 반환
//수퍼클래스
class Rectangle {
constructor(width,height) {
this.width = width;
this. height = height;
}
getArea() {
return this.width * this.height;
}
toString() {
return `width = ${this.width}, height = ${this.height}`;
}
}
//서브클래스
class ColorRectangle extneds Rectangle {
constructor(width, height, color) {
super(width, height);
this.color = colorl
}
//메서드 오버라이딩
toString() {
return super.toString() + `, color = ${this.color}`;
}
}
const colorRectangle = new ColorRectangle(2, 4, 'red');
console.log(colorRectangle); // ColorRectangle {width : 2, height:4, color: 'red'}
//상속을 통해 getArea 메서드 호출
console.log(colorRectangle.getArea()); //8
//상속을 통해 toString 메서드를 호출
console.log(colorRectangle.toString()); // width = 2, height = 4, color = red
// Array 생성자 함수를 상속받아 확장
class MyArray extends Array {
static get [Symbol.species]() { return Array; }
// 중복된 배열 요소를 제거하고 반환: [1,1,2,3] => [1,2,3]
uniq() {
return this.filter((v, i , self) => self.indexOf(v) === i);
}
// 모든 배열 요소의 평균을 구한다: [1,2,3] => 2
average() {
return this.reduce((pre, cur) => pre + cur, 0 ) / this.length;
}
}
const myArray = new MyArray(1,1,2,3);
console.log(myArray); // MyArray(4) [1,1,2,3]
// // MyArray.prototype.uniq 호출
console.log(myArray.uniq()); // MyArray(3) [1,2,3]
// MyArray.prototype.average 호출
console.log(myArray.average()); // 1.75
// 주의할 점. Array.prototype 메서드 중 map, filter와 같은 새로운 배열을 반환하는 메서드는 MyArray 클래스의 인스턴스를 반환한다.
conosle.log(myArray.filter(v => v % 2) instanceof MyArray); // true
// 왜 그래야만 하냐면, 만약 filter가 Array를 반환하면, uniq(), average() 함수와 메서드 체이닝이 불가능할 것.
// 메서드 체이닝
// [1,1,2,3] => [1,1,3] => [1,3] => 2
console.log(myArray.filter(v => v % 2).uniq().average()); // 2
// 만약 MyArray가 아닌, Array가 생성한 인스턴스를 반환하고 싶다면, 다음 코드를 클래스 안에 추가할 것. 단, 메서드 체이닝은 포기해야 한다.
static get [Symbol.species]() { return Array; ]