class Person {
constructor(name, age) {
this.name = name;
this.age = age;
this.country = 'Korea';
}
}
let person1 = new Person('김철수', 25);
console.log(person1.name); // 김철수
console.log(person1.age); // 25
console.log(person1.country); // Korea
클래스를 통해 생성된 객체를 인스턴스(instance)라고 부른다.
new 키워드와 소괄호()를 이용해 클래스를 호출할 수 있다.
클래스 이름은 항상 대문자로 시작한다.
생성자 (constructor)는 기초 정보를 세팅하는 곳이다 클래스를 호출할 때, 가장 먼저 자동으로 호출된다.
this는 자기 자신의 객체를 의미한다.클래스 몸체에 정의한 메서드는 프로토 타입 메서드가 된다.
생성자 함수와 클래스의 차이점
new와 함께 호출하지 않으면 에러가 발생한다.속성에 접근하거나 값을 설정할 때 함수처럼 동작하지만, 속성처럼 사용도 할 수 있는 메서드이다.
getter
get을 이용해 선언 한다.setter
set을 이용해 선언 한다getter와 setter는 왜 사용해야 할까?
class Temperature {
constructor(celsius = 0) {
this._celsius = celsius;
}
get celsius() {
return this._celsius;
}
set celsius(temp) {
this._celsius = temp;
}
get fahrenheit() {
return (this._celsius * 9/5) + 32;
}
set fahrenheit(temp) {
this._celsius = (temp - 32) * 5/9;
}
}
const temp = new Temperature(25);
console.log(`섭씨: ${temp.celsius}°C`); // 섭씨: 25°C
console.log(`화씨: ${temp.fahrenheit}°F`); // 화씨: 77°F
클래스의 인스턴스가 아닌 클래스 자체에 속하는 method와 property를 정의할 때 사용된다.
static이라는 키워드를 붙인다.new 생성자로 인스턴스 객체를 생성하지 않아도 해당 method와 property를 사용할 수 있다.this 키워드를 이용해 상위 오프젝트에 접근할 수 없다.class A{
static a(){
코드
}
}
class Calculator {
static max(a, b) {
return a > b ? a : b;
}
static min(a, b) {
return a < b ? a : b;
}
}
console.log(Calculator.max(1, 2)); // 2
class User {
static count = 0;
static maxUsers = 10;
}
console.log(User.count); // 0
console.log(User.maxUsers); // 10
기존의 클래스를 재사용해 새로운 클래스를 만드는 방법이다.
// 사람
class Person {
constructor(name, age, location) {
this.name = name;
this.age = age;
this.location = location;
this.speak = function() {
return `안녕하세요, 저는 ${this.name}입니다.`;
};
}
}
// 배우 (사람을 상속)
class Actor extends Person {
constructor(name, age, location) {
super(name, age, location);
this.act = function() {
return `${this.name}가 연기를 합니다.`;
};
}
}
const person = new Person("김철수", 30, "서울");
const actor = new Actor("차은우", 25, "부산");
console.log(person.speak()); // 안녕하세요, 저는 김철수입니다.
console.log(actor.speak()); // 안녕하세요, 저는 차은우입니다.
console.log(actor.act()); // 차은우가 연기를 합니다.
extendsextends 클래스명의 형태로 어디에서 상속을 받아올 지 지정한다.constructorsuperPerson의 속성인 name, age, location을 호출해 접근한다.super()를 사용했을 때에는 상위 클래스의 constructor를 호출한다.this 키워드보다 먼저 사용해야 한다 아닐 시 오류 발생