ES6에 도입된 자바스크립트 클래스는 자바스크립트 프로토타입 기반 상속에 대한 문법적 설탕입니다. 클래스는 실제로 "특수 기능"입니다. 다음 구문을 사용하여 class 키워드를 사용하여 JavaScript에서 클래스를 정의할 수 있습니다. -
class Person {
// Constructor for this class
constructor(name) {
this.name = name;
}
// an instance method on this class
displayName() {
console.log(this.name)
}
} 이것은 본질적으로 다음 선언과 동일합니다 -
let Person = function(name) {
this.name = name;
}
Person.prototype.displayName = function() {
console.log(this.name)
} 이 클래스는 클래스 표현식으로 작성할 수도 있습니다. 위의 형식은 클래스 선언입니다. 다음 형식은 클래스 표현식입니다 -
// Unnamed expression
let Person = class {
// Constructor for this class
constructor(name) {
this.name = name;
}
// an instance method on this class
displayName() {
console.log(this.name)
}
} 위에서 언급한 대로 클래스를 어떻게 정의하든 다음을 사용하여 이러한 클래스의 개체를 만들 수 있습니다. -
예시
let John = new Person("John");
John.displayName(); 출력
John
https://www.tutorialspoint.com/es6/es6_classes.htm에서 JS 클래스와 class 키워드에 대해 자세히 읽을 수 있습니다.