[Javascript] ES6 class
Updated:
ES6 class
// Person : parent class
// extends : inheritance between classes, automatically sets prototype
class Student extends Person {
university = "KNU"; // public field
_studyHours = 0; // private filed
_course;
static numSubjects = 10; // static public field
// constructor method, called by new operator
constructor(fullName, birthYear, startYear, course) {
super(fullName, birthYear); // call to parent class
this.startYear = startYear; // instance property
this._course = course; // redefining private field
}
// public method
introduce() {
console.log(`hi I am ${this.fullName}`);
}
study(h) {
// Referencing private field and method
this._makeCoffe();
this._studyHours += h;
}
_makeCoffe() {
return "coffee for you";
}
// getter and setter method
get testScore() {
return this._testScore;
}
// use _ to set property with same name as method
set testScore(score) {
this._testScore = score <= 20 ? score : 0;
}
// static method (cannot access instance properties nor method)
static printCurriculum() {
console.log(`There are ${this.numSubjects} subjects`);
}
}
- extends 키워드를 이용하여 상속
- private 변수, 메서드는 보통 under bar
_
를 쓰는데, 이것은 그냥 convention임 - static 키워드를 이용하여 인스턴스가 아니라 class 자체에서 호출가능
ref :
Class basic syntax
Leave a comment