class 는 비슷한 object 를 빠르게 만들기 위한 tool
class 를 이용하면 중복된 코드를 없애고 디버깅하는 시간을 줄일 수 있다
객체와 클래스를 구분하는 가장 중요한 메소드 : constructor
자바스크립트에서, 클래스에 새로운 인스턴스를 생성할 때 무조건 constructor method 를 부른다
class Dog {
constructor(name) {
this.name = name;
this.behavior = 0;
}
}
An instance is an object that contains the property names and methods of a class, but with unique property values
인스턴스 = 객체
인스턴스는 프로퍼티 이름과 메소드를 가지고 있다
유일한 프로퍼티 값을 가지고 있다
class Surgeon {
constructor(name, department) {
this.name = name;
this.department = department;
}
}
const surgeonCurry = new Surgeon('Curry', 'Cardiovascular');
const surgeonDurant = new Surgeon('Durant', 'Orthopedics');
클래스 메서드와 getter 구문은 객체의 메서드, getter 구문과 같다.
유일한 다른 점은 메서드 사이에 , 콤마를 붙이지 않는다는 것이다.
class Dog {
constructor(name) {
this._name = name;
this._behavior = 0;
}
// 여기에 , 콤마가 없다
get name() {
return this._name;
}
get behavior() {
return this._behavior;
}
incrementBehavior() {
this._behavior++;
}
}
메서드와 getter 를 불러오려면
인스턴스.메서드()
혹은 인스턴스.getter
하면 된다.
// calling getter
console.log(surgeon.name);
// calling method
surjeonCurry.takeVacationDays(3);
class Cat extends Animal {
constructor(name, usesLitter) {
super(name);
this._usesLitter = usesLitter;
}
}
인스턴스에 상관없이 부모 클래스에서 직접 받아서 쓸 수 있는 메서드를 만들고 싶다면 static method 를 생성하면 된다.
static generatePassword() {
return Math.floor(Math.random() * 10000);
}