Using classes - JavaScript | MDN
new연산자와 함께 사용되어 인스턴스를 만드는 생성자constructor로서의 역할을 한다. new operator & constructor
JavaScript에서 클래스는 사실 “special function”이다, 즉 함수의 한 종류이다. 함수를 funciton expressions와 function declarations, 두가지 방법으로 정의할 수 있는 것처럼, 클래스 역시 마찬가지로 expressions(const Rectangle = class{} 방식)과 declarations(class Rectangle {} 방식) 두가지 방법으로 정의할 수 있다.
// Declaration
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
// Expression; the class is anonymous but assigned to a variable
const Rectangle = class {
constructor(height, width) {
this.height = height;
this.width = width;
}
};
// Expression; the class has its own name
const Rectangle = class Rectangle2 {
constructor(height, width) {
this.height = height;
this.width = width;
}
};
다만 클래스가 단순히 함수의 편의 문법syntactic sugar같은 개념은 아니다. (몇몇 사람들은 생성자 함수 기능을 하는 일반 함수를 정의하여 new와 함께 사용하면 클래스와 거의 유사한 효과를 낼 수 있기 때문에 클래스를 단순히 함수의 syntactic sugar라고 이야기 하는데, 그건 사실이 아니라는 이야기이다. 일반 함수와는 분명히 다른 차이점이 있다 - 참고)
a JavaScript class is in fact a special type of function - 클래스가 함수라는 증거
const x = function() {}
Object.getPrototypeOf(x); // ƒ () { [native code] }
const y = class {}
Object.getPrototypeOf(y); // ƒ () { [native code] }
class User {
constructor(name) { this.name = name; }
sayHi() { alert(this.name); }
}
// User가 함수라는 증거
alert(typeof User); // function
typeof 만 해봐도 빼박 함수다.class 정의는 (expression이든 declaration이든) let, const와 마찬가지로 temporal dead zone에 있는 것처럼 취급된다.
{} 안의 내용을 가리킨다. class members, 즉 methods, fields, constructor 등이 여기에 위치한다.
class body는 “use strict”가 없더라도 항상 strict mode로 실행된다.
class element들은 다음과 같은 세가지 관점으로 분류할 수 있다.
⇒ 이들의 조합에 따라 총 16가지(422)의 경우가 있다고 볼 수 있다. (e.g. public instance getter)
이중 MDN에 별개 문서가 있는 항목들로는 method definitions, getter, setter, public class fields, static, private properties가 있다.
여기에 더해, 특별한 class element syntax가 두가지 더 있다. 바로..
constructor는 해당 클래스를 기반으로 생성되는 객체(인스턴스)를 생성하고 초기화(initialize)하기 위한 특수한 메소드이다. (즉 constructor도 일단은 메소드다)
constructor”라는 이름을 가진 메소드는 한 클래스에 하나만 있을 수 있다. (두개 이상이 있을 경우 SyntaxError 발생)constructor에서는 super 키워드를 사용하여 super class의 constructor를 호출할 수 있다.
constructor에서는 인자로 받은 값과 this를 사용하여 instance properties 또한 생성할 수 있다. 예를들면 아래처럼 말이다.
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
static {} 이렇게 사용하는 문법. instance initialization동안에 body안의 statements들을 실행시킬 수 있기 때문에 flexible initialization이 가능하다. this를 통해 내부 프로퍼티(private포함)에 접근할 수 있다 .