들어가기 앞서 : 생성자함수와 클래스의 차이점
https://sunshineyellow.tistory.com/18?category=1037372
[코딩앙마 외] 객체 리터럴과 객체 접근법, 그리고 생성자 함수
객체를 생성하는 방법에는 두 가지가 있다. 객체 리터럴 생성자 함수 단 하나의 객체만을 생성할 때는 직관적이고 간편한 객체 리터럴을 사용하고, 같은 객체를 대량생산할 때는 생성자함수를
sunshineyellow.tistory.com
위 글에서 객체와 생성자함수를 간단하게 공부했다.
그렇다면 생성자함수와 다른 클래스의 특이점은 무엇일까?
- 클래스는 new 연산자 없이는 호출이 불가능하다.
- 클래스는 extends(클래스의 상속)와 super(super클래스의 constructor과 method 호출)를 쓸 수 있다.
- 클래스는 자동으로 strict mode로 실행되며 호이스팅은 되나 TDZ가 발생해 선언 전에 호출할 수 없다.
클래스 (class)
클래스는 객체를 생성하기 위한 템플릿이다.
let Goodcoder = class {
//constructor
constructor(name, age) {
this.name = name;
this.age = age;
}
//method
coding() {
console.log(`${this.name}, good job!`);
}
};
클래스 안에는 클래스로 생성된 객체를 생성하고 초기화할 수 있는 생성자(constructor)가 한 개만 들어갈 수 있다. (여러개의 constructor 메서드가 들어가면 SyntaxError가 발생한다.)
또한 method(https://sunshineyellow.tistory.com/17에서도 공부했다)가 들어갈 수 있다.
함수를 선언하기 위해 함수선언문과 함수표현식을 쓰듯, 클래스를 선언하기 위해서도 클래스선언문과 클래스표현식이 있다.
클래스선언문
class Goodcoder {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
클래스선언문은 함수선언문과 다르게 클래스가 호이스팅될 때 초기화되지 않기 때문에 선언하기 전에 사용할 수 없다.
const noran = new Goodcoder //ReferenceError
class Goodcoder {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
클래스표현식
클래스선언문과 동일한 호이스팅을 적용받아 선언하기 전에 사용할 수 없다.
unnamed
let Goodcoder = class {
constructor(name, age) {
this.name = name;
this.age = age;
}
};
console.log(Goodcoder.name); //Goodcoder를 출력한다.
named
let Goodcoder = class Goodcoder2 {
constructor(name, age) {
this.name = name;
this.age = age;
}
};
console.log(Goodcoder.name); //Goodcoder2를 출력한다.
name을 가진 class의 name은 class body({}로 묶여있는 부분)의 local scope에 한해 유효하다.
출처 : 드림코딩 https://www.youtube.com/@dream-coding / MDN https://developer.mozilla.org/ko
'🟨 JavaScript > 개념' 카테고리의 다른 글
| [mdn, 드림코딩 외] 객체지향 (3) : 정적 속성과 메소드(static properties and methods) (0) | 2022.05.04 |
|---|---|
| [mdn, 드림코딩 외] 객체지향 (2) : 객체(object)와 getter and setter (0) | 2022.05.04 |
| [드림코딩 외] 콜백함수 (Callback function) (0) | 2022.04.22 |
| [드림코딩] Early return, early exit? (0) | 2022.04.21 |
| [드림코딩, comp110 외] 매개변수 (parameters)와 나머지 매개변수(rest parameters) (0) | 2022.04.18 |